From a23fb4733c250b2be0124ad456af7da71f4fca00 Mon Sep 17 00:00:00 2001 From: Fawn Date: Mon, 13 Jan 2020 17:03:19 -0500 Subject: started creating mobile ink view --- src/server/authentication/models/current_user_utils.ts | 1 + 1 file changed, 1 insertion(+) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 2ade6f102..71369b625 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -101,6 +101,7 @@ export class CurrentUserUtils { { title: "use eraser", icon: "eraser", click: 'activateEraser(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "pink", activePen: doc }, { title: "use scrubber", icon: "eraser", click: 'activateScrubber(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "green", activePen: doc }, { title: "use drag", icon: "mouse-pointer", click: 'deactivateInk();this.activePen.pen = this;', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "white", activePen: doc }, + { title: "draw", icon: "mouse-pointer", click: 'switchMobileView("ink");', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "red", activePen: doc }, ]; return docProtoData.filter(d => !buttons || !buttons.includes(d.title)).map(data => Docs.Create.FontIconDocument({ nativeWidth: 100, nativeHeight: 100, width: 100, height: 100, dropAction: data.click ? "copy" : undefined, title: data.title, icon: data.icon, ignoreClick: data.ignoreClick, -- cgit v1.2.3-70-g09d2 From b4c2d2add2b863060ce559e49b3953f24050f162 Mon Sep 17 00:00:00 2001 From: Fawn Date: Tue, 14 Jan 2020 14:47:44 -0500 Subject: can add strokes to mobile ink --- src/client/views/collections/CollectionSubView.tsx | 3 +- .../collectionFreeForm/CollectionFreeFormView.tsx | 1 + src/mobile/MobileInterface.tsx | 108 +++++++++++++++------ .../authentication/models/current_user_utils.ts | 4 + 4 files changed, 87 insertions(+), 29 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index 73dc7edc6..d8b575092 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -53,7 +53,9 @@ export function CollectionSubView(schemaCtor: (doc: Doc) => T) { protected createDropAndGestureTarget = (ele: HTMLDivElement) => { //used for stacking and masonry view this.dropDisposer && this.dropDisposer(); this.gestureDisposer && this.gestureDisposer(); + console.log("create drop", ele); if (ele) { + console.log("create drop 2", ele); this.dropDisposer = DragManager.MakeDropTarget(ele, this.drop.bind(this)); this.gestureDisposer = GestureUtils.MakeGestureTarget(ele, this.onGesture.bind(this)); } @@ -135,7 +137,6 @@ export function CollectionSubView(schemaCtor: (doc: Doc) => T) { @undoBatch protected onGesture(e: Event, ge: GestureUtils.GestureEvent) { - } @undoBatch diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 84945c6e6..c3e131184 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -356,6 +356,7 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { @undoBatch onGesture = (e: Event, ge: GestureUtils.GestureEvent) => { + console.log("on gesture"); switch (ge.gesture) { case GestureUtils.Gestures.Stroke: const points = ge.points; diff --git a/src/mobile/MobileInterface.tsx b/src/mobile/MobileInterface.tsx index 1e0920686..8d342d749 100644 --- a/src/mobile/MobileInterface.tsx +++ b/src/mobile/MobileInterface.tsx @@ -10,8 +10,10 @@ import { DocumentView } from '../client/views/nodes/DocumentView'; import { emptyPath, emptyFunction, returnFalse, returnOne, returnEmptyString, returnTrue } from '../Utils'; import { Transform } from '../client/util/Transform'; import { library } from '@fortawesome/fontawesome-svg-core'; -import { faPenNib, faHighlighter, faEraser, faMousePointer } from '@fortawesome/free-solid-svg-icons'; +import { faPenNib, faHighlighter, faEraser, faMousePointer, faBreadSlice } from '@fortawesome/free-solid-svg-icons'; import { Scripting } from '../client/util/Scripting'; +import { CollectionFreeFormView } from '../client/views/collections/collectionFreeForm/CollectionFreeFormView'; +import GestureOverlay from '../client/views/GestureOverlay'; @observer export default class MobileInterface extends React.Component { @@ -35,52 +37,102 @@ export default class MobileInterface extends React.Component { } } - @action switchCurrentView = (view: "main" | "ink" | "library") => { this.currentView = view; } + @action + switchCurrentView = (view: "main" | "ink" | "library") => { + this.currentView = view; + + if (this.userDoc) { + switch (view) { + case "main": { + const doc = CurrentUserUtils.setupMobileDoc(this.userDoc); + this.userDoc.activeMobile = doc; + break; + } + case "ink": { + const doc = CurrentUserUtils.setupMobileInkingDoc(this.userDoc); + this.userDoc.activeMobile = doc; + break; + } + } + } + } @computed get mainContent() { if (this.mainContainer) { - switch (this.currentView) { - case "main": - return window.screen.width} + PanelHeight={() => window.screen.height} + renderDepth={0} + focus={emptyFunction} + backgroundColor={returnEmptyString} + parentActive={returnTrue} + whenActiveChanged={emptyFunction} + bringToFront={emptyFunction} + ContainingCollectionView={undefined} + ContainingCollectionDoc={undefined} + zoomToScale={emptyFunction} + getScale={returnOne}> + ; + } + return "hello"; + } + + @computed + get inkContent() { + // return
INK
; + if (this.mainContainer) { + return ( + + window.screen.width} PanelHeight={() => window.screen.height} - renderDepth={0} + PanelWidth={() => window.screen.width} + annotationsKey={""} + isAnnotationOverlay={false} focus={emptyFunction} - backgroundColor={returnEmptyString} - parentActive={returnTrue} - whenActiveChanged={emptyFunction} - bringToFront={emptyFunction} + isSelected={returnTrue} // + select={emptyFunction} + active={returnTrue} // + ContentScaling={returnOne} + whenActiveChanged={returnFalse} + CollectionView={undefined} + ScreenToLocalTransform={Transform.Identity} + ruleProvider={undefined} + renderDepth={0} ContainingCollectionView={undefined} ContainingCollectionDoc={undefined} - zoomToScale={emptyFunction} - getScale={returnOne}> - ; - case "ink": - return
INK
; - case "library": - return
LIBRARY
; - } + chromeCollapsed={true}> +
+
+ ); } - return "hello"; } render() { - console.log("rendering mobile"); + const content = this.currentView === "main" ? this.mainContent : this.currentView === "ink" ? this.inkContent : <>; return (
- {this.mainContent} + {content}
); } diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 71369b625..b40179fbc 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -140,6 +140,10 @@ export class CurrentUserUtils { }); } + static setupMobileInkingDoc(userDoc: Doc) { + return Docs.Create.FreeformDocument([], { x: 0, y: 0, width: 10, height: 20, title: "Mobile Inking", backgroundColor: "red" }); + } + // setup the Creator button which will display the creator panel. This panel will include the drag creators and the color picker. when clicked, this panel will be displayed in the target container (ie, sidebarContainer) static setupToolsPanel(sidebarContainer: Doc, doc: Doc) { // setup a masonry view of all he creators -- cgit v1.2.3-70-g09d2 From 3cca58612cde96a3082ca8e190fe2166d531d556 Mon Sep 17 00:00:00 2001 From: Fawn Date: Tue, 14 Jan 2020 17:40:50 -0500 Subject: drawn strokes get added to mobile ink collection --- src/client/views/GestureOverlay.tsx | 2 +- src/client/views/collections/CollectionSubView.tsx | 2 - .../collectionFreeForm/CollectionFreeFormView.tsx | 8 +-- src/mobile/MobileInterface.scss | 7 +++ src/mobile/MobileInterface.tsx | 62 ++++++++++++++-------- .../authentication/models/current_user_utils.ts | 2 +- 6 files changed, 53 insertions(+), 30 deletions(-) create mode 100644 src/mobile/MobileInterface.scss (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/views/GestureOverlay.tsx b/src/client/views/GestureOverlay.tsx index 632f2f0d6..4d487c032 100644 --- a/src/client/views/GestureOverlay.tsx +++ b/src/client/views/GestureOverlay.tsx @@ -231,9 +231,9 @@ export default class GestureOverlay extends Touchable { render() { return (
+ {this.currentStroke} {this.props.children} {this._palette} - {this.currentStroke}
); } } diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index d8b575092..e94f24f2c 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -53,9 +53,7 @@ export function CollectionSubView(schemaCtor: (doc: Doc) => T) { protected createDropAndGestureTarget = (ele: HTMLDivElement) => { //used for stacking and masonry view this.dropDisposer && this.dropDisposer(); this.gestureDisposer && this.gestureDisposer(); - console.log("create drop", ele); if (ele) { - console.log("create drop 2", ele); this.dropDisposer = DragManager.MakeDropTarget(ele, this.drop.bind(this)); this.gestureDisposer = GestureUtils.MakeGestureTarget(ele, this.onGesture.bind(this)); } diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index c3e131184..8d376fb57 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -114,6 +114,7 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { } private addDocument = (newBox: Doc) => { const added = this.props.addDocument(newBox); + console.log("adding doc from freeform", added); added && this.bringToFront(newBox); added && this.updateCluster(newBox); return added; @@ -356,12 +357,12 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { @undoBatch onGesture = (e: Event, ge: GestureUtils.GestureEvent) => { - console.log("on gesture"); switch (ge.gesture) { case GestureUtils.Gestures.Stroke: const points = ge.points; const B = this.getTransform().transformBounds(ge.bounds.left, ge.bounds.top, ge.bounds.width, ge.bounds.height); const inkDoc = Docs.Create.InkDocument(InkingControl.Instance.selectedColor, InkingControl.Instance.selectedTool, parseInt(InkingControl.Instance.selectedWidth), points, { x: B.x, y: B.y, width: B.width, height: B.height }); + console.log("make stroke", inkDoc); this.addDocument(inkDoc); e.stopPropagation(); break; @@ -403,14 +404,14 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { @action pan = (e: PointerEvent | React.Touch | { clientX: number, clientY: number }): void => { // I think it makes sense for the marquee menu to go away when panned. -syip2 - MarqueeOptionsMenu.Instance.fadeOut(true); + MarqueeOptionsMenu.Instance && MarqueeOptionsMenu.Instance.fadeOut(true); let x = this.Document.panX || 0; let y = this.Document.panY || 0; const docs = this.childLayoutPairs.map(pair => pair.layout); const [dx, dy] = this.getTransform().transformDirection(e.clientX - this._lastX, e.clientY - this._lastY); if (!this.isAnnotationOverlay) { - PDFMenu.Instance.fadeOut(true); + PDFMenu.Instance && PDFMenu.Instance.fadeOut(true); const minx = docs.length ? NumCast(docs[0].x) : 0; const maxx = docs.length ? NumCast(docs[0].width) + minx : minx; const miny = docs.length ? NumCast(docs[0].y) : 0; @@ -990,6 +991,7 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { // otherwise, they are stored in fieldKey. All annotations to this document are stored in the extension document if (!this.extensionDoc) return (null); // let lodarea = this.Document[WidthSym]() * this.Document[HeightSym]() / this.props.ScreenToLocalTransform().Scale / this.props.ScreenToLocalTransform().Scale; + console.log("height freeform", this.isAnnotationOverlay, this.Document.scrollHeight, this.props.PanelHeight()); return
diff --git a/src/mobile/MobileInterface.scss b/src/mobile/MobileInterface.scss new file mode 100644 index 000000000..e4cc919a5 --- /dev/null +++ b/src/mobile/MobileInterface.scss @@ -0,0 +1,7 @@ +.mobileInterface-topButtons { + position: absolute; + display: flex; + justify-content: space-between; + width: 100%; + z-index: 9999; +} \ No newline at end of file diff --git a/src/mobile/MobileInterface.tsx b/src/mobile/MobileInterface.tsx index 8d342d749..3cb08afa7 100644 --- a/src/mobile/MobileInterface.tsx +++ b/src/mobile/MobileInterface.tsx @@ -10,10 +10,16 @@ import { DocumentView } from '../client/views/nodes/DocumentView'; import { emptyPath, emptyFunction, returnFalse, returnOne, returnEmptyString, returnTrue } from '../Utils'; import { Transform } from '../client/util/Transform'; import { library } from '@fortawesome/fontawesome-svg-core'; -import { faPenNib, faHighlighter, faEraser, faMousePointer, faBreadSlice } from '@fortawesome/free-solid-svg-icons'; +import { faPenNib, faHighlighter, faEraser, faMousePointer, faBreadSlice, faTrash, faCheck } from '@fortawesome/free-solid-svg-icons'; import { Scripting } from '../client/util/Scripting'; import { CollectionFreeFormView } from '../client/views/collections/collectionFreeForm/CollectionFreeFormView'; import GestureOverlay from '../client/views/GestureOverlay'; +import { InkingControl } from '../client/views/InkingControl'; +import { InkTool } from '../new_fields/InkField'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import "./MobileInterface.scss"; + +library.add(faTrash, faCheck); @observer export default class MobileInterface extends React.Component { @@ -22,6 +28,9 @@ export default class MobileInterface extends React.Component { @computed private get mainContainer() { return this.userDoc ? FieldValue(Cast(this.userDoc.activeMobile, Doc)) : CurrentUserUtils.GuestMobile; } @observable private currentView: "main" | "ink" | "library" = "main"; + private mainDoc = CurrentUserUtils.setupMobileDoc(this.userDoc); + private inkDoc?: Doc; + constructor(props: Readonly<{}>) { super(props); MobileInterface.Instance = this; @@ -32,8 +41,8 @@ export default class MobileInterface extends React.Component { library.add(...[faPenNib, faHighlighter, faEraser, faMousePointer]); if (this.userDoc && !this.mainContainer) { - const doc = CurrentUserUtils.setupMobileDoc(this.userDoc); - this.userDoc.activeMobile = doc; + // const doc = CurrentUserUtils.setupMobileDoc(this.userDoc); + this.userDoc.activeMobile = this.mainDoc; } } @@ -44,13 +53,14 @@ export default class MobileInterface extends React.Component { if (this.userDoc) { switch (view) { case "main": { - const doc = CurrentUserUtils.setupMobileDoc(this.userDoc); - this.userDoc.activeMobile = doc; + // const doc = CurrentUserUtils.setupMobileDoc(this.userDoc); + this.userDoc.activeMobile = this.mainDoc; break; } case "ink": { - const doc = CurrentUserUtils.setupMobileInkingDoc(this.userDoc); - this.userDoc.activeMobile = doc; + this.inkDoc = CurrentUserUtils.setupMobileInkingDoc(this.userDoc); + this.userDoc.activeMobile = this.inkDoc; + InkingControl.Instance.switchTool(InkTool.Pen); break; } } @@ -64,7 +74,7 @@ export default class MobileInterface extends React.Component { Document={this.mainContainer} DataDoc={undefined} LibraryPath={emptyPath} - addDocument={undefined} + addDocument={returnFalse} addDocTab={returnFalse} pinToPres={emptyFunction} removeDocument={undefined} @@ -89,40 +99,46 @@ export default class MobileInterface extends React.Component { return "hello"; } + onClick = (e: React.MouseEvent) => { + // insert ink as collection into active displayed doc view + // reset ink collection + this.inkDoc = undefined; + console.log("clicked"); + this.switchCurrentView("main"); + InkingControl.Instance.switchTool(InkTool.None); // TODO: switch to previous tool + } + @computed get inkContent() { - // return
INK
; + // TODO: get props from active collection and pass to the new freeform if (this.mainContainer) { return ( - + + +
+ window.screen.height} - PanelWidth={() => window.screen.width} - annotationsKey={""} - isAnnotationOverlay={false} + PanelHeight={() => window.innerHeight} + PanelWidth={() => window.innerWidth} focus={emptyFunction} - isSelected={returnTrue} // + isSelected={returnTrue} select={emptyFunction} - active={returnTrue} // + active={returnTrue} ContentScaling={returnOne} whenActiveChanged={returnFalse} - CollectionView={undefined} ScreenToLocalTransform={Transform.Identity} ruleProvider={undefined} renderDepth={0} ContainingCollectionView={undefined} - ContainingCollectionDoc={undefined} - chromeCollapsed={true}> - + ContainingCollectionDoc={undefined}> + ); } diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index b40179fbc..98092ddfe 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -141,7 +141,7 @@ export class CurrentUserUtils { } static setupMobileInkingDoc(userDoc: Doc) { - return Docs.Create.FreeformDocument([], { x: 0, y: 0, width: 10, height: 20, title: "Mobile Inking", backgroundColor: "red" }); + return Docs.Create.FreeformDocument([], { title: "Mobile Inking", backgroundColor: "white" }); } // setup the Creator button which will display the creator panel. This panel will include the drag creators and the color picker. when clicked, this panel will be displayed in the target container (ie, sidebarContainer) -- cgit v1.2.3-70-g09d2 From f4662822d9dd3280e843c3f088aee310352705ae Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Fri, 31 Jan 2020 09:03:55 -0500 Subject: streamlined presentationview --- .../views/collections/CollectionDockingView.tsx | 2 +- src/client/views/nodes/PresBox.scss | 4 +--- src/client/views/nodes/PresBox.tsx | 6 +++--- .../views/presentationview/PresElementBox.scss | 20 +++++++++++++++----- .../authentication/models/current_user_utils.ts | 2 +- 5 files changed, 21 insertions(+), 13 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 82cb3bc88..159a1cded 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -643,7 +643,7 @@ export class DockedFrameRenderer extends React.Component { //add this new doc to props.Document const curPres = Cast(CurrentUserUtils.UserDocument.curPresentation, Doc) as Doc; if (curPres) { - const pinDoc = Docs.Create.PresElementBoxDocument({ backgroundColor: "transparent" }); + const pinDoc = Docs.Create.PresElementBoxDocument({ backgroundColor: "transparent", _xMargin: 5 }); Doc.GetProto(pinDoc).presentationTargetDoc = doc; Doc.GetProto(pinDoc).title = ComputedField.MakeFunction('(this.presentationTargetDoc instanceof Doc) && this.presentationTargetDoc.title?.toString()'); const data = Cast(curPres.data, listSpec(Doc)); diff --git a/src/client/views/nodes/PresBox.scss b/src/client/views/nodes/PresBox.scss index e5a79ab11..01e7f4834 100644 --- a/src/client/views/nodes/PresBox.scss +++ b/src/client/views/nodes/PresBox.scss @@ -6,7 +6,7 @@ top: 0; bottom: 0; width: 100%; - min-width: 200px; + min-width: 100px; height: 100%; min-height: 50px; letter-spacing: 2px; @@ -16,8 +16,6 @@ .presBox-listCont { position: relative; - padding-left: 10px; - padding-right: 10px; } .presBox-buttons { diff --git a/src/client/views/nodes/PresBox.tsx b/src/client/views/nodes/PresBox.tsx index 428e9aa7b..8d53f45a6 100644 --- a/src/client/views/nodes/PresBox.tsx +++ b/src/client/views/nodes/PresBox.tsx @@ -42,7 +42,7 @@ export class PresBox extends React.Component { if (value) { value.forEach((item, i) => { if (item instanceof Doc && item.type !== DocumentType.PRESELEMENT) { - const pinDoc = Docs.Create.PresElementBoxDocument({ backgroundColor: "transparent" }); + const pinDoc = Docs.Create.PresElementBoxDocument({ backgroundColor: "transparent", _xMargin: 5 }); Doc.GetProto(pinDoc).presentationTargetDoc = item; Doc.GetProto(pinDoc).title = ComputedField.MakeFunction('this.presentationTargetDoc?.title?.toString()'); value.splice(i, 1, pinDoc); @@ -337,7 +337,7 @@ export class PresBox extends React.Component { @action initializeScaleViews = (docList: Doc[], viewtype: number) => { this.props.Document._chromeStatus = "disabled"; - const hgt = (viewtype === CollectionViewType.Tree) ? 50 : 72; + const hgt = (viewtype === CollectionViewType.Tree) ? 50 : 42; docList.forEach((doc: Doc) => { doc.presBox = this.props.Document; doc.presBoxKey = this.props.fieldKey; @@ -357,7 +357,7 @@ export class PresBox extends React.Component { } getTransform = () => { - return this.props.ScreenToLocalTransform().translate(-10, -50);// listBox padding-left and pres-box-cont minHeight + return this.props.ScreenToLocalTransform().translate(0, -50);// listBox padding-left and pres-box-cont minHeight } render() { this.initializeScaleViews(this.childDocs, NumCast(this.props.Document._viewType)); diff --git a/src/client/views/presentationview/PresElementBox.scss b/src/client/views/presentationview/PresElementBox.scss index ac78babef..b74b07224 100644 --- a/src/client/views/presentationview/PresElementBox.scss +++ b/src/client/views/presentationview/PresElementBox.scss @@ -6,14 +6,17 @@ width: 100%; outline-color: maroon; outline-style: dashed; - border-radius: 12px; + border-radius: 6px; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; - transition: all .1s; + transition: all .1s; + padding: 0px; + padding-left: 5px; + padding-bottom: 3px; .documentView-node { position: absolute; @@ -32,13 +35,13 @@ .presElementBox-item:hover { transition: all .1s; background: #AAAAAA; - border-radius: 12px; + border-radius: 6px; } .presElementBox-selected { background: gray; color: black; - border-radius: 12px; + border-radius: 6px; box-shadow: black 2px 2px 5px; } @@ -48,20 +51,27 @@ position: absolute; right: 0; top: 0; + padding: 8px; } .presElementBox-interaction { color: gray; float: left; + padding: 0px; + width: 20px; + height: 20px; } .presElementBox-interaction-selected { color: white; float: left; + padding: 0px; + width: 22px; + height: 22px; } .presElementBox-name { - font-size: 15px; + font-size: 12px; position: absolute; display: inline-block; width: calc(100% - 45px); diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index dbde351b3..6bfc729de 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -55,7 +55,7 @@ export class CurrentUserUtils { { title: "cat image", icon: "cat", ignoreClick: true, drag: 'Docs.Create.ImageDocument("https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg", { _width: 200, title: "an image of a cat" })' }, { title: "record", icon: "microphone", ignoreClick: true, drag: `Docs.Create.AudioDocument("${nullAudio}", { _width: 200, title: "ready to record audio" })` }, { title: "clickable button", icon: "bolt", ignoreClick: true, drag: 'Docs.Create.ButtonDocument({ _width: 150, _height: 50, title: "Button" })' }, - { title: "presentation", icon: "tv", ignoreClick: true, drag: `Doc.UserDoc().curPresentation = Docs.Create.PresDocument(new List(), { _width: 200, _height: 500, _viewType: ${CollectionViewType.Stacking}, title: "a presentation trail" })` }, + { title: "presentation", icon: "tv", ignoreClick: true, drag: `Doc.UserDoc().curPresentation = Docs.Create.PresDocument(new List(), { _width: 200, _height: 500, _xMargin:5, _viewType: ${CollectionViewType.Stacking}, title: "a presentation trail" })` }, { title: "import folder", icon: "cloud-upload-alt", ignoreClick: true, drag: 'Docs.Create.DirectoryImportDocument({ title: "Directory Import", _width: 400, _height: 400 })' }, { title: "mobile view", icon: "phone", ignoreClick: true, drag: 'Doc.UserDoc().activeMobile' }, { title: "use pen", icon: "pen-nib", click: 'activatePen(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this,2, this.backgroundColor)', backgroundColor: "blue", ischecked: `sameDocs(this.activePen.pen, this)`, activePen: doc }, -- cgit v1.2.3-70-g09d2 From 7249f3f2bd12794ca86775853aee700e398eeb00 Mon Sep 17 00:00:00 2001 From: vellichora Date: Sun, 2 Feb 2020 16:13:23 -0500 Subject: started creating upload from web on mobile --- src/client/DocServer.ts | 6 +- src/mobile/MobileInkOverlay.tsx | 15 ++--- src/mobile/MobileInterface.tsx | 72 ++++++++++++++++++++-- src/server/Message.ts | 4 +- src/server/Websocket/Websocket.ts | 7 ++- .../authentication/models/current_user_utils.ts | 14 ++++- 6 files changed, 99 insertions(+), 19 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/DocServer.ts b/src/client/DocServer.ts index b20cd3521..c03764471 100644 --- a/src/client/DocServer.ts +++ b/src/client/DocServer.ts @@ -1,5 +1,5 @@ import * as OpenSocket from 'socket.io-client'; -import { MessageStore, YoutubeQueryTypes, GestureContent, MobileInkOverlayContent, UpdateMobileInkOverlayPosition } from "./../server/Message"; +import { MessageStore, YoutubeQueryTypes, GestureContent, MobileInkOverlayContent, UpdateMobileInkOverlayPositionContent } from "./../server/Message"; import { Opt, Doc } from '../new_fields/Doc'; import { Utils, emptyFunction } from '../Utils'; import { SerializationHelper } from './util/SerializationHelper'; @@ -77,7 +77,7 @@ export namespace DocServer { Utils.Emit(_socket, MessageStore.MobileInkOverlayTrigger, content); } - export function dispatchOverlayPositionUpdate(content: UpdateMobileInkOverlayPosition) { + export function dispatchOverlayPositionUpdate(content: UpdateMobileInkOverlayPositionContent) { Utils.Emit(_socket, MessageStore.UpdateMobileInkOverlayPosition, content); } @@ -113,7 +113,7 @@ export namespace DocServer { GestureOverlay.Instance.enableMobileInkOverlay(content); MobileInkOverlay.Instance.initMobileInkOverlay(content); }); - _socket.addEventListener("updateMobileOverlayPosition", (content: UpdateMobileInkOverlayPosition) => { + _socket.addEventListener("receiveUpdateOverlayPosition", (content: UpdateMobileInkOverlayPositionContent) => { MobileInkOverlay.Instance.updatePosition(content); }); } diff --git a/src/mobile/MobileInkOverlay.tsx b/src/mobile/MobileInkOverlay.tsx index 5efc7b83a..600e8a91b 100644 --- a/src/mobile/MobileInkOverlay.tsx +++ b/src/mobile/MobileInkOverlay.tsx @@ -1,6 +1,6 @@ import React = require('react'); import { observer } from "mobx-react"; -import { MobileInkOverlayContent, GestureContent, UpdateMobileInkOverlayPosition } from "../server/Message"; +import { MobileInkOverlayContent, GestureContent, UpdateMobileInkOverlayPositionContent } from "../server/Message"; import { observable, action } from "mobx"; import { GestureUtils } from "../pen-gestures/GestureUtils"; import "./MobileInkOverlay.scss"; @@ -37,17 +37,19 @@ export default class MobileInkOverlay extends React.Component { initMobileInkOverlay(content: MobileInkOverlayContent) { const { width, height } = content; const scaledSize = this.initialSize(width ? width : 0, height ? height : 0); - this._width = scaledSize.width * .5; - this._height = scaledSize.height * .5; - this._scale = .5; //scaledSize.scale; + this._width = scaledSize.width * .8; + this._height = scaledSize.height * .8; + this._scale = .8; //scaledSize.scale; this._x = 300; // TODO: center on screen this._y = 25; // TODO: center on screen } @action - updatePosition(content: UpdateMobileInkOverlayPosition) { + updatePosition(content: UpdateMobileInkOverlayPositionContent) { const { dx, dy, dsize } = content; - console.log(dx, dy, dsize); + if (dx) this._x += dx; + if (dy) this._y += dy; + // TODO: scale dsize } drawStroke = (content: GestureContent) => { @@ -82,7 +84,6 @@ export default class MobileInkOverlay extends React.Component { @action dragStart = (e: React.PointerEvent) => { - console.log("pointer down"); document.removeEventListener("pointermove", this.dragging); document.removeEventListener("pointerup", this.dragEnd); document.addEventListener("pointermove", this.dragging); diff --git a/src/mobile/MobileInterface.tsx b/src/mobile/MobileInterface.tsx index b191b3afb..03bcbca80 100644 --- a/src/mobile/MobileInterface.tsx +++ b/src/mobile/MobileInterface.tsx @@ -30,12 +30,15 @@ export default class MobileInterface extends React.Component { @observable static Instance: MobileInterface; @computed private get userDoc() { return CurrentUserUtils.UserDocument; } @computed private get mainContainer() { return this.userDoc ? FieldValue(Cast(this.userDoc.activeMobile, Doc)) : CurrentUserUtils.GuestMobile; } - @observable private currentView: "main" | "ink" | "library" = "main"; + @observable private currentView: "main" | "ink" | "upload" = "main"; private mainDoc = CurrentUserUtils.setupMobileDoc(this.userDoc); + private inkDoc?: Doc; public drawingInk: boolean = false; + private uploadDoc?: Doc; + constructor(props: Readonly<{}>) { super(props); MobileInterface.Instance = this; @@ -52,7 +55,7 @@ export default class MobileInterface extends React.Component { } @action - switchCurrentView = (view: "main" | "ink" | "library") => { + switchCurrentView = (view: "main" | "ink" | "upload") => { this.currentView = view; if (this.userDoc) { @@ -76,6 +79,11 @@ export default class MobileInterface extends React.Component { break; } + case "upload": { + this.uploadDoc = CurrentUserUtils.setupMobileUploadDoc(this.userDoc); + this.userDoc.activeMobile = this.uploadDoc; + + } } } } @@ -127,15 +135,20 @@ export default class MobileInterface extends React.Component { } shiftLeft = (e: React.MouseEvent) => { + console.log("shift left!"); DocServer.Mobile.dispatchOverlayPositionUpdate({ dx: -10 }); + e.preventDefault(); + e.stopPropagation(); } shiftRight = (e: React.MouseEvent) => { DocServer.Mobile.dispatchOverlayPositionUpdate({ dx: 10 }); + e.preventDefault(); + e.stopPropagation(); } @computed @@ -147,7 +160,7 @@ export default class MobileInterface extends React.Component {
- +
@@ -185,8 +198,57 @@ export default class MobileInterface extends React.Component { } } + upload = () => { + + } + + @computed + get uploadContent() { + if (this.mainContainer) { + return ( +
+
+
+ +
+
+ +
+
+ window.screen.width} + PanelHeight={() => window.screen.height} + renderDepth={0} + focus={emptyFunction} + backgroundColor={returnEmptyString} + parentActive={returnTrue} + whenActiveChanged={emptyFunction} + bringToFront={emptyFunction} + ContainingCollectionView={undefined} + ContainingCollectionDoc={undefined} + zoomToScale={emptyFunction} + getScale={returnOne}> + +
+ ); + } + } + render() { - const content = this.currentView === "main" ? this.mainContent : this.currentView === "ink" ? this.inkContent : <>; + const content = this.currentView === "main" ? this.mainContent : + this.currentView === "ink" ? this.inkContent : + this.currentView === "upload" ? this.uploadContent : <>; return (
{content} @@ -195,4 +257,4 @@ export default class MobileInterface extends React.Component { } } -Scripting.addGlobal(function switchMobileView(view: "main" | "ink" | "library") { return MobileInterface.Instance.switchCurrentView(view); }); +Scripting.addGlobal(function switchMobileView(view: "main" | "ink" | "upload") { return MobileInterface.Instance.switchCurrentView(view); }); diff --git a/src/server/Message.ts b/src/server/Message.ts index 064a19653..236df3f3c 100644 --- a/src/server/Message.ts +++ b/src/server/Message.ts @@ -56,7 +56,7 @@ export interface MobileInkOverlayContent { readonly height?: number; } -export interface UpdateMobileInkOverlayPosition { +export interface UpdateMobileInkOverlayPositionContent { readonly dx?: number; readonly dy?: number; readonly dsize?: number; @@ -74,7 +74,7 @@ export namespace MessageStore { export const GesturePoints = new Message("Gesture Points"); export const MobileInkOverlayTrigger = new Message("Trigger Mobile Ink Overlay"); - export const UpdateMobileInkOverlayPosition = new Message("Update Mobile Ink Overlay Position"); + export const UpdateMobileInkOverlayPosition = new Message("Update Mobile Ink Overlay Position"); export const GetRefField = new Message("Get Ref Field"); export const GetRefFields = new Message("Get Ref Fields"); diff --git a/src/server/Websocket/Websocket.ts b/src/server/Websocket/Websocket.ts index fe253400c..77816c897 100644 --- a/src/server/Websocket/Websocket.ts +++ b/src/server/Websocket/Websocket.ts @@ -1,5 +1,5 @@ import { Utils } from "../../Utils"; -import { MessageStore, Transferable, Types, Diff, YoutubeQueryInput, YoutubeQueryTypes, GestureContent, MobileInkOverlayContent } from "../Message"; +import { MessageStore, Transferable, Types, Diff, YoutubeQueryInput, YoutubeQueryTypes, GestureContent, MobileInkOverlayContent, UpdateMobileInkOverlayPositionContent } from "../Message"; import { Client } from "../Client"; import { Socket } from "socket.io"; import { Database } from "../database"; @@ -56,6 +56,7 @@ export namespace WebSocket { Utils.AddServerHandler(socket, MessageStore.DeleteFields, ids => DeleteFields(socket, ids)); Utils.AddServerHandler(socket, MessageStore.GesturePoints, content => processGesturePoints(socket, content)); Utils.AddServerHandler(socket, MessageStore.MobileInkOverlayTrigger, content => processOverlayTrigger(socket, content)); + Utils.AddServerHandler(socket, MessageStore.UpdateMobileInkOverlayPosition, content => processUpdateOverlayPosition(socket, content)); Utils.AddServerHandlerCallback(socket, MessageStore.GetRefField, GetRefField); Utils.AddServerHandlerCallback(socket, MessageStore.GetRefFields, GetRefFields); @@ -78,6 +79,10 @@ export namespace WebSocket { socket.broadcast.emit("receiveOverlayTrigger", content); } + function processUpdateOverlayPosition(socket: Socket, content: UpdateMobileInkOverlayPositionContent) { + socket.broadcast.emit("receiveUpdateOverlayPosition", content); + } + function HandleYoutubeQuery([query, callback]: [YoutubeQueryInput, (result?: any[]) => void]) { const { ProjectCredentials } = GoogleCredentialsLoader; switch (query.type) { diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 98092ddfe..82bed76f7 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -101,7 +101,8 @@ export class CurrentUserUtils { { title: "use eraser", icon: "eraser", click: 'activateEraser(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "pink", activePen: doc }, { title: "use scrubber", icon: "eraser", click: 'activateScrubber(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "green", activePen: doc }, { title: "use drag", icon: "mouse-pointer", click: 'deactivateInk();this.activePen.pen = this;', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "white", activePen: doc }, - { title: "draw", icon: "mouse-pointer", click: 'switchMobileView("ink");', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "red", activePen: doc }, + { title: "draw", icon: "pen-nib", click: 'switchMobileView("ink");', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "red", activePen: doc }, + { title: "upload", icon: "upload", click: 'switchMobileView("upload");', backgroundColor: "orange" }, ]; return docProtoData.filter(d => !buttons || !buttons.includes(d.title)).map(data => Docs.Create.FontIconDocument({ nativeWidth: 100, nativeHeight: 100, width: 100, height: 100, dropAction: data.click ? "copy" : undefined, title: data.title, icon: data.icon, ignoreClick: data.ignoreClick, @@ -144,6 +145,17 @@ export class CurrentUserUtils { return Docs.Create.FreeformDocument([], { title: "Mobile Inking", backgroundColor: "white" }); } + static setupMobileUploadDoc(userDoc: Doc) { + console.log("setup mobile upload", window.innerWidth, window.innerHeight); + const webDoc = Docs.Create.WebDocument("https://wikipedia.com", { title: "Mobile Upload Web", chromeStatus: "enabled", ignoreClick: true }); + const uploadDoc = Docs.Create.StackingDocument([], { title: "Mobile Upload", backgroundColor: "pink" }); + return Docs.Create.StackingDocument([webDoc, uploadDoc], { + title: "Mobile Upload", backgroundColor: "white", + columnWidth: window.innerWidth, ignoreClick: true, lockedPosition: true, chromeStatus: "disabled", autoHeight: true, yMargin: 5, + width: window.innerWidth, height: window.innerHeight + }); + } + // setup the Creator button which will display the creator panel. This panel will include the drag creators and the color picker. when clicked, this panel will be displayed in the target container (ie, sidebarContainer) static setupToolsPanel(sidebarContainer: Doc, doc: Doc) { // setup a masonry view of all he creators -- cgit v1.2.3-70-g09d2 From da92903fb49b2c7d34bb44f11bf72a6cd49b8c0d Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Tue, 4 Feb 2020 23:52:40 -0500 Subject: lots of small fixes to templates, presentations, default templates (icon, slide) --- src/client/views/MainView.tsx | 2 +- src/client/views/OverlayView.tsx | 2 +- .../views/collections/CollectionTimeView.tsx | 10 ++++---- .../CollectionMulticolumnView.scss | 1 + .../CollectionMulticolumnView.tsx | 13 ++++++---- .../CollectionMultirowView.scss | 1 + .../CollectionMultirowView.tsx | 12 ++++++---- src/client/views/nodes/DocumentView.tsx | 28 ++++++++++------------ src/client/views/nodes/PresBox.scss | 2 +- src/client/views/nodes/PresBox.tsx | 8 +++++-- .../views/presentationview/PresElementBox.tsx | 2 +- src/new_fields/Doc.ts | 16 +++++++++---- .../authentication/models/current_user_utils.ts | 20 +++++++++++++++- 13 files changed, 78 insertions(+), 39 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 87a81504c..0cc374cee 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -1,6 +1,6 @@ import { library } from '@fortawesome/fontawesome-svg-core'; import { - faArrowDown, faBullseye, faFilter, faArrowUp, faBolt, faCaretUp, faCat, faCheck, faChevronRight, faClone, faCloudUploadAlt, faCommentAlt, faCut, faEllipsisV, faExclamation, faFilePdf, faFilm, faFont, faGlobeAsia, faLongArrowAltRight, + faStickyNote, faArrowDown, faBullseye, faFilter, faArrowUp, faBolt, faCaretUp, faCat, faCheck, faChevronRight, faClone, faCloudUploadAlt, faCommentAlt, faCut, faEllipsisV, faExclamation, faFilePdf, faFilm, faFont, faGlobeAsia, faLongArrowAltRight, faMusic, faObjectGroup, faPause, faMousePointer, faPenNib, faFileAudio, faPen, faEraser, faPlay, faPortrait, faRedoAlt, faThumbtack, faTree, faTv, faUndoAlt, faHighlighter, faMicrophone, faCompressArrowsAlt, faPhone, faStamp, faClipboard } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; diff --git a/src/client/views/OverlayView.tsx b/src/client/views/OverlayView.tsx index 295cd7c6e..7a99bf0ae 100644 --- a/src/client/views/OverlayView.tsx +++ b/src/client/views/OverlayView.tsx @@ -144,7 +144,7 @@ export class OverlayView extends React.Component { return (null); } return CurrentUserUtils.UserDocument.overlays instanceof Doc && DocListCast(CurrentUserUtils.UserDocument.overlays.data).map(d => { - d.inOverlay = true; + setTimeout(() => d.inOverlay = true, 0); let offsetx = 0, offsety = 0; const onPointerMove = action((e: PointerEvent) => { if (e.buttons === 1) { diff --git a/src/client/views/collections/CollectionTimeView.tsx b/src/client/views/collections/CollectionTimeView.tsx index f999067d3..264423d72 100644 --- a/src/client/views/collections/CollectionTimeView.tsx +++ b/src/client/views/collections/CollectionTimeView.tsx @@ -46,6 +46,7 @@ export class CollectionTimeView extends CollectionSubView(doc => doc) { @computed get _allFacets() { const facets = new Set(); this.childDocs.forEach(child => Object.keys(Doc.GetProto(child)).forEach(key => facets.add(key))); + Doc.AreProtosEqual(this.dataDoc, this.props.Document) && this.childDocs.forEach(child => Object.keys(child).forEach(key => facets.add(key))); return facets.toArray(); } @@ -108,11 +109,10 @@ export class CollectionTimeView extends CollectionSubView(doc => doc) { const docItems: ContextMenuProps[] = []; const keySet: Set = new Set(); - this.childLayoutPairs.map(pair => - Array.from(Object.keys(Doc.GetProto(pair.layout))).filter(fieldKey => - pair.layout[fieldKey] instanceof RichTextField || - typeof (pair.layout[fieldKey]) === "number" || - typeof (pair.layout[fieldKey]) === "string").map(fieldKey => keySet.add(fieldKey))); + this.childLayoutPairs.map(pair => this._allFacets.filter(fieldKey => + pair.layout[fieldKey] instanceof RichTextField || + typeof (pair.layout[fieldKey]) === "number" || + typeof (pair.layout[fieldKey]) === "string").map(fieldKey => keySet.add(fieldKey))); keySet.toArray().map(fieldKey => docItems.push({ description: ":" + fieldKey, event: () => this.props.Document.pivotField = fieldKey, icon: "compress-arrows-alt" })); docItems.push({ description: ":(null)", event: () => this.props.Document.pivotField = undefined, icon: "compress-arrows-alt" }) diff --git a/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.scss b/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.scss index f57ba438a..a5d5617bc 100644 --- a/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.scss +++ b/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.scss @@ -7,6 +7,7 @@ .document-wrapper { display: flex; flex-direction: column; + width: 100%; .label-wrapper { display: flex; diff --git a/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx b/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx index cbe064ec0..56f777f43 100644 --- a/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx +++ b/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx @@ -224,10 +224,11 @@ export class CollectionMulticolumnView extends CollectionSubView(MulticolumnDocu Document={layout} DataDocument={layout.resolvedDataDoc as Doc} CollectionDoc={this.props.Document} - PanelWidth={() => this.lookupPixels(layout)} - PanelHeight={() => PanelHeight() - (BoolCast(Document.showWidthLabels) ? 20 : 0)} - getTransform={() => this.lookupIndividualTransform(layout)} + PanelWidth={() => this.lookupPixels(layout) - 2 * NumCast(Document._xMargin)} + PanelHeight={() => PanelHeight() - 2 * NumCast(Document._yMargin) - (BoolCast(Document.showWidthLabels) ? 20 : 0)} + getTransform={() => this.lookupIndividualTransform(layout).translate(-NumCast(Document._xMargin), -NumCast(Document._yMargin))} onClick={this.onChildClickHandler} + renderDepth={this.props.renderDepth + 1} /> +
{this.contents}
); diff --git a/src/client/views/collections/collectionMulticolumn/CollectionMultirowView.scss b/src/client/views/collections/collectionMulticolumn/CollectionMultirowView.scss index ef4b4a19c..ed737ea59 100644 --- a/src/client/views/collections/collectionMulticolumn/CollectionMultirowView.scss +++ b/src/client/views/collections/collectionMulticolumn/CollectionMultirowView.scss @@ -8,6 +8,7 @@ .document-wrapper { display: flex; flex-direction: row; + height: 100%; .label-wrapper { display: flex; diff --git a/src/client/views/collections/collectionMulticolumn/CollectionMultirowView.tsx b/src/client/views/collections/collectionMulticolumn/CollectionMultirowView.tsx index 434bf14ff..8a2498458 100644 --- a/src/client/views/collections/collectionMulticolumn/CollectionMultirowView.tsx +++ b/src/client/views/collections/collectionMulticolumn/CollectionMultirowView.tsx @@ -224,9 +224,9 @@ export class CollectionMultirowView extends CollectionSubView(MultirowDocument) Document={layout} DataDocument={layout.resolvedDataDoc as Doc} CollectionDoc={this.props.Document} - PanelHeight={() => this.lookupPixels(layout)} - PanelWidth={() => PanelWidth() - (BoolCast(Document.showHeightLabels) ? 20 : 0)} - getTransform={() => this.lookupIndividualTransform(layout)} + PanelHeight={() => this.lookupPixels(layout) - 2 * NumCast(Document._yMargin)} + PanelWidth={() => PanelWidth() - 2 * NumCast(Document._xMargin) - (BoolCast(Document.showHeightLabels) ? 20 : 0)} + getTransform={() => this.lookupIndividualTransform(layout).translate(-NumCast(Document._xMargin), -NumCast(Document._yMargin))} onClick={this.onChildClickHandler} renderDepth={this.props.renderDepth + 1} /> @@ -250,7 +250,11 @@ export class CollectionMultirowView extends CollectionSubView(MultirowDocument) render(): JSX.Element { return ( -
+
{this.contents}
); diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index d768dd7cf..c14d11cce 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -111,7 +111,7 @@ export class DocumentView extends DocComponent(Docu @computed get topMost() { return this.props.renderDepth === 0; } @computed get nativeWidth() { return this.layoutDoc._nativeWidth || 0; } @computed get nativeHeight() { return this.layoutDoc._nativeHeight || 0; } - @computed get onClickHandler() { return this.props.onClick ? this.props.onClick : this.Document.onClick; } + @computed get onClickHandler() { return this.props.onClick || this.layoutDoc.onClick || this.Document.onClick; } @computed get onPointerDownHandler() { return this.props.onPointerDown ? this.props.onPointerDown : this.Document.onPointerDown; } @computed get onPointerUpHandler() { return this.props.onPointerUp ? this.props.onPointerUp : this.Document.onPointerUp; } @@ -520,11 +520,8 @@ export class DocumentView extends DocComponent(Docu @undoBatch deleteClicked = (): void => { SelectionManager.DeselectAll(); this.props.removeDocument && this.props.removeDocument(this.props.Document); } - static makeNativeViewClicked = (doc: Doc, prevLayout: string) => { - undoBatch(() => { - if (StrCast(doc.title).endsWith("_" + prevLayout)) doc.title = StrCast(doc.title).replace("_" + prevLayout, ""); - doc.layoutKey = "layout"; - })(); + static makeNativeViewClicked = (doc: Doc) => { + undoBatch(() => Doc.setNativeView(doc))(); } static makeCustomViewClicked = (doc: Doc, dataDoc: Opt, creator: (documents: Array, options: DocumentOptions, id?: string) => Doc, name: string = "custom", docLayoutTemplate?: Doc) => { @@ -653,21 +650,22 @@ export class DocumentView extends DocComponent(Docu @action setCustomView = (custom: boolean, layout: string): void => { - if (this.props.ContainingCollectionView?.props.DataDoc || this.props.ContainingCollectionView?.props.Document.isTemplateDoc) { - Doc.MakeMetadataFieldTemplate(this.props.Document, this.props.ContainingCollectionView.props.Document); - } else if (custom) { - DocumentView.makeNativeViewClicked(this.props.Document, StrCast(this.props.Document.layoutKey).split("_")[1]); - - let foundLayout: Opt = undefined; - DocListCast(Cast(CurrentUserUtils.UserDocument.expandingButtons, Doc, null)?.data)?.map(btnDoc => { + // if (this.props.ContainingCollectionView?.props.DataDoc || this.props.ContainingCollectionView?.props.Document.isTemplateDoc) { + // Doc.MakeMetadataFieldTemplate(this.props.Document, this.props.ContainingCollectionView.props.Document); + // } else + if (custom) { + DocumentView.makeNativeViewClicked(this.props.Document); + + let foundLayout: Opt = Cast(Doc.UserDoc().iconView, Doc, null); + !foundLayout && DocListCast(Cast(CurrentUserUtils.UserDocument.expandingButtons, Doc, null)?.data)?.map(btnDoc => { if (StrCast(Cast(btnDoc?.dragFactory, Doc, null)?.title) === layout) { foundLayout = btnDoc.dragFactory as Doc; } }) DocumentView. - makeCustomViewClicked(this.props.Document, this.props.DataDoc, Docs.Create.StackingDocument, layout, foundLayout && Doc.MakeDelegate(foundLayout)); + makeCustomViewClicked(this.props.Document, this.props.DataDoc, Docs.Create.StackingDocument, layout, foundLayout); } else { - DocumentView.makeNativeViewClicked(this.props.Document, StrCast(this.props.Document.layoutKey).split("_")[1]); + DocumentView.makeNativeViewClicked(this.props.Document); } } diff --git a/src/client/views/nodes/PresBox.scss b/src/client/views/nodes/PresBox.scss index 01e7f4834..3e1967a18 100644 --- a/src/client/views/nodes/PresBox.scss +++ b/src/client/views/nodes/PresBox.scss @@ -6,7 +6,7 @@ top: 0; bottom: 0; width: 100%; - min-width: 100px; + min-width: 120px; height: 100%; min-height: 50px; letter-spacing: 2px; diff --git a/src/client/views/nodes/PresBox.tsx b/src/client/views/nodes/PresBox.tsx index 06d8e688b..44411fa30 100644 --- a/src/client/views/nodes/PresBox.tsx +++ b/src/client/views/nodes/PresBox.tsx @@ -6,7 +6,6 @@ import { action, computed, IReactionDisposer, reaction } from "mobx"; import { observer } from "mobx-react"; import { Doc, DocListCast, DocListCastAsync } from "../../../new_fields/Doc"; import { listSpec } from "../../../new_fields/Schema"; -import { ComputedField } from "../../../new_fields/ScriptField"; import { Cast, FieldValue, NumCast } from "../../../new_fields/Types"; import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; import { Docs } from "../../documents/Documents"; @@ -17,7 +16,6 @@ import { CollectionView, CollectionViewType } from "../collections/CollectionVie import { ContextMenu } from "../ContextMenu"; import { FieldView, FieldViewProps } from './FieldView'; import "./PresBox.scss"; -import { presSchema } from "../presentationview/PresElementBox"; library.add(faArrowLeft); library.add(faArrowRight); @@ -31,6 +29,7 @@ library.add(faEdit); @observer export class PresBox extends React.Component { public static LayoutString(fieldKey: string) { return FieldView.LayoutString(PresBox, fieldKey); } + _childReaction: IReactionDisposer | undefined; componentDidMount() { const userDoc = CurrentUserUtils.UserDocument; let presTemp = Cast(userDoc.presentationTemplate, Doc); @@ -43,6 +42,11 @@ export class PresBox extends React.Component { else { this.props.Document.childLayout = presTemp; } + this._childReaction = reaction(() => this.childDocs.slice(), + (children) => children.forEach((child, i) => child.presentationIndex = i), { fireImmediately: true }); + } + componentWillUnmount() { + this._childReaction?.(); } @computed get childDocs() { return DocListCast(this.props.Document[this.props.fieldKey]); } diff --git a/src/client/views/presentationview/PresElementBox.tsx b/src/client/views/presentationview/PresElementBox.tsx index dcc5247d5..ea3acf75c 100644 --- a/src/client/views/presentationview/PresElementBox.tsx +++ b/src/client/views/presentationview/PresElementBox.tsx @@ -50,7 +50,7 @@ export class PresElementBox extends DocExtendableComponent d instanceof Doc && MakeMetadataFieldTemplate(d, templateDoc)); (Doc.GetProto(templateField)[metadataFieldKey] = ObjectField.MakeCopy(templateField.data)); } - if (templateField.data instanceof RichTextField && templateField.data.Text) { + if (templateField.data instanceof RichTextField && (templateField.data.Text || templateField.data.Data.toString().includes("dashField"))) { templateField._textTemplate = ComputedField.MakeFunction(`copyField(this.${metadataFieldKey})`, { this: Doc.name }); } @@ -780,6 +781,12 @@ export namespace Doc { const fieldStr = Field.toString(fieldVal as Field); return fieldStr === value; } + + export function setNativeView(doc: any) { + const prevLayout = StrCast(doc.layoutKey).split("_")[1]; + if (StrCast(doc.title).endsWith("_" + prevLayout)) doc.title = StrCast(doc.title).replace("_" + prevLayout, ""); + doc.layoutKey = "layout"; + } } Scripting.addGlobal(function renameAlias(doc: any, n: any) { return StrCast(Doc.GetProto(doc).title).replace(/\([0-9]*\)/, "") + `(${n})`; }); @@ -792,6 +799,7 @@ Scripting.addGlobal(function copyField(field: any) { return ObjectField.MakeCopy Scripting.addGlobal(function aliasDocs(field: any) { return new List(field.map((d: any) => Doc.MakeAlias(d))); }); Scripting.addGlobal(function docList(field: any) { return DocListCast(field); }); Scripting.addGlobal(function sameDocs(doc1: any, doc2: any) { return Doc.AreProtosEqual(doc1, doc2); }); +Scripting.addGlobal(function setNativeView(doc: any) { Doc.setNativeView(doc); }); Scripting.addGlobal(function undo() { return UndoManager.Undo(); }); Scripting.addGlobal(function redo() { return UndoManager.Redo(); }); Scripting.addGlobal(function selectDoc(doc: any) { Doc.UserDoc().SelectedDocs = new List([doc]); }); diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 6bfc729de..f2c3aab35 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -15,6 +15,8 @@ import { nullAudio } from "../../../new_fields/URLField"; import { DragManager } from "../../../client/util/DragManager"; import { InkingControl } from "../../../client/views/InkingControl"; import { CollectionViewType } from "../../../client/views/collections/CollectionView"; +import { makeTemplate } from "../../../client/util/DropConverter"; +import { RichTextField } from "../../../new_fields/RichTextField"; export class CurrentUserUtils { private static curr_id: string; @@ -227,14 +229,30 @@ export class CurrentUserUtils { /// sets up the default list of buttons to be shown in the expanding button menu at the bottom of the Dash window static setupExpandingButtons(doc: Doc) { + const slideTemplate = Docs.Create.StackingDocument( + [ + Docs.Create.MulticolumnDocument([], { title: "images", _height: 200, _xMargin: 10, _yMargin: 10 }), + Docs.Create.TextDocument("", { title: "contents", _height: 100 }) + ], + { _width: 400, _height: 300, title: "slide", _chromeStatus: "disabled", _autoHeight: true }); + slideTemplate.isTemplateDoc = makeTemplate(slideTemplate); + + const iconDoc = Docs.Create.TextDocument("", { title: "icon", _width: 150, _height: 30, onClick: ScriptField.MakeScript("setNativeView(this)") }); + Doc.GetProto(iconDoc).data = new RichTextField('{"doc":{"type":"doc","content":[{"type":"paragraph","attrs":{"align":null,"color":null,"id":null,"indent":null,"inset":null,"lineSpacing":null,"paddingBottom":null,"paddingTop":null},"content":[{"type":"dashField","attrs":{"fieldKey":"title","docid":""}}]}]},"selection":{"type":"text","anchor":2,"head":2},"storedMarks":[]}', ""); + doc.isTemplateDoc = makeTemplate(iconDoc); + doc.iconView = iconDoc; + doc.undoBtn = Docs.Create.FontIconDocument( { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, _dropAction: "alias", onClick: ScriptField.MakeScript("undo()"), removeDropProperties: new List(["dropAction"]), title: "undo button", icon: "undo-alt" }); doc.redoBtn = Docs.Create.FontIconDocument( { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, _dropAction: "alias", onClick: ScriptField.MakeScript("redo()"), removeDropProperties: new List(["dropAction"]), title: "redo button", icon: "redo-alt" }); + doc.slidesBtn = Docs.Create.FontIconDocument( + { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, _dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: slideTemplate, removeDropProperties: new List(["dropAction"]), title: "slide button", icon: "sticky-note" }); - doc.expandingButtons = Docs.Create.LinearDocument([doc.undoBtn as Doc, doc.redoBtn as Doc], { + doc.expandingButtons = Docs.Create.LinearDocument([doc.undoBtn as Doc, doc.redoBtn as Doc, doc.slidesBtn as Doc], { title: "expanding buttons", _gridGap: 5, _xMargin: 5, _yMargin: 5, _height: 42, _width: 100, boxShadow: "0 0", backgroundColor: "black", preventTreeViewOpen: true, forceActive: true, lockedPosition: true, + dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }) }); } -- cgit v1.2.3-70-g09d2 From 6c7d337d64bca66456c617986e03f44bc5d807d8 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Wed, 5 Feb 2020 08:35:58 -0500 Subject: added pin to pres button. --- src/client/views/DocumentButtonBar.tsx | 27 +++++++++++++++++++++- .../views/collections/CollectionDockingView.tsx | 19 ++++++++++++--- .../authentication/models/current_user_utils.ts | 9 ++++++++ 3 files changed, 51 insertions(+), 4 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx index 65d1ade2a..121f79840 100644 --- a/src/client/views/DocumentButtonBar.tsx +++ b/src/client/views/DocumentButtonBar.tsx @@ -11,7 +11,7 @@ import { emptyFunction } from "../../Utils"; import { Pulls, Pushes } from '../apis/google_docs/GoogleApiClientUtils'; import RichTextMenu from '../util/RichTextMenu'; import { UndoManager } from "../util/UndoManager"; -import { CollectionDockingView } from './collections/CollectionDockingView'; +import { CollectionDockingView, DockedFrameRenderer } from './collections/CollectionDockingView'; import { ParentDocSelector } from './collections/ParentDocumentSelector'; import './collections/ParentDocumentSelector.scss'; import './DocumentButtonBar.scss'; @@ -23,6 +23,7 @@ import { Template, Templates } from "./Templates"; import React = require("react"); import { DragManager } from '../util/DragManager'; import { MetadataEntryMenu } from './MetadataEntryMenu'; +import { CurrentUserUtils } from '../../server/authentication/models/current_user_utils'; const higflyout = require("@hig/flyout"); export const { anchorPoints } = higflyout; export const Flyout = higflyout.default; @@ -197,6 +198,26 @@ export class DocumentButtonBar extends React.Component<{ views: (DocumentView | />
; } + @computed + get pinButton() { + const targetDoc = this.view0?.props.Document; + const isPinned = targetDoc && CurrentUserUtils.IsDocPinned(targetDoc); + return !targetDoc ? (null) :
{ + if (isPinned) { + DockedFrameRenderer.UnpinDoc(targetDoc); + } + else { + DockedFrameRenderer.PinDoc(targetDoc); + } + }}> + +
; + } @computed get linkButton() { @@ -294,6 +315,7 @@ export class DocumentButtonBar extends React.Component<{ views: (DocumentView | const isText = this.view0.props.Document.data instanceof RichTextField; // bcz: Todo - can't assume layout is using the 'data' field. need to add fieldKey to DocumentView const considerPull = isText && this.considerGoogleDocsPull; const considerPush = isText && this.considerGoogleDocsPush; + Doc.UserDoc().pr return
{this.linkButton} @@ -307,6 +329,9 @@ export class DocumentButtonBar extends React.Component<{ views: (DocumentView |
{this.contextButton}
+
+ {this.pinButton} +
{this.considerGoogleDocsPush}
diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 152710cd0..861a63503 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -635,7 +635,7 @@ export class DockedFrameRenderer extends React.Component { **/ @undoBatch @action - public PinDoc(doc: Doc) { + public static PinDoc(doc: Doc) { //add this new doc to props.Document const curPres = Cast(CurrentUserUtils.UserDocument.curPresentation, Doc) as Doc; if (curPres) { @@ -643,10 +643,23 @@ export class DockedFrameRenderer extends React.Component { pinDoc.presentationTargetDoc = doc; Doc.AddDocToList(curPres, "data", pinDoc); if (!DocumentManager.Instance.getDocumentView(curPres)) { - this.addDocTab(curPres, undefined, "onRight"); + CollectionDockingView.AddRightSplit(curPres, undefined); } } } + /** + * Adds a document to the presentation view + **/ + @undoBatch + @action + public static UnpinDoc(doc: Doc) { + //add this new doc to props.Document + const curPres = Cast(CurrentUserUtils.UserDocument.curPresentation, Doc) as Doc; + if (curPres) { + const ind = DocListCast(curPres.data).findIndex((val) => Doc.AreProtosEqual(val, doc)); + ind !== -1 && Doc.RemoveDocFromList(curPres, "data", DocListCast(curPres.data)[ind]); + } + } componentDidMount() { const observer = new _global.ResizeObserver(action((entries: any) => { @@ -743,7 +756,7 @@ export class DockedFrameRenderer extends React.Component { focus={emptyFunction} backgroundColor={returnEmptyString} addDocTab={this.addDocTab} - pinToPres={this.PinDoc} + pinToPres={DockedFrameRenderer.PinDoc} ContainingCollectionView={undefined} ContainingCollectionDoc={undefined} zoomToScale={emptyFunction} diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index f2c3aab35..a6dd809f4 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -304,6 +304,15 @@ export class CurrentUserUtils { return doc; } + public static IsDocPinned(doc: Doc) { + //add this new doc to props.Document + const curPres = Cast(CurrentUserUtils.UserDocument.curPresentation, Doc) as Doc; + if (curPres) { + return DocListCast(curPres.data).findIndex((val) => Doc.AreProtosEqual(val, doc)) !== -1; + } + return false; + } + public static async loadCurrentUser() { return rp.get(Utils.prepend("/getCurrentUser")).then(response => { if (response) { -- cgit v1.2.3-70-g09d2 From a0ca191b6263e3ccff8740ddf6cf9cba68b9f2f9 Mon Sep 17 00:00:00 2001 From: bob Date: Wed, 5 Feb 2020 11:26:24 -0500 Subject: fixed iconify things. fixed presentation title bar. --- src/client/documents/Documents.ts | 3 ++- src/client/views/DocumentDecorations.tsx | 3 ++- src/client/views/nodes/DocumentView.tsx | 2 +- src/new_fields/Doc.ts | 4 +++- src/server/authentication/models/current_user_utils.ts | 11 +++++++---- 5 files changed, 15 insertions(+), 8 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 5eb4dc5fb..17570fcb5 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -106,6 +106,7 @@ export interface DocumentOptions { documentText?: string; borderRounding?: string; boxShadow?: string; + showTitle?: string; sectionFilter?: string; // field key used to determine headings for sections in stacking and masonry views schemaColumns?: List; dockingConfig?: string; @@ -340,7 +341,7 @@ export namespace Docs { export namespace Create { const delegateKeys = ["x", "y", "layoutKey", "_width", "_height", "_panX", "_panY", "_viewType", "_nativeWidth", "_nativeHeight", "_dropAction", "_annotationOn", - "_chromeStatus", "_forceActive", "_autoHeight", "_fitWidth", "_LODdisable", "_itemIndex", "_showSidebar"]; + "_chromeStatus", "_forceActive", "_autoHeight", "_fitWidth", "_LODdisable", "_itemIndex", "_showSidebar", "showTitle"]; /** * This function receives the relevant document prototype and uses diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index c5034b901..a0ba16ea4 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -265,8 +265,8 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> const layoutKey = Cast(dv.props.Document.layoutKey, "string", null); const collapse = layoutKey !== "layout_icon"; if (collapse) { - if (layoutKey && layoutKey !== "layout") dv.props.Document.deiconifyLayout = layoutKey.replace("layout_", ""); dv.setCustomView(collapse, "icon"); + if (layoutKey && layoutKey !== "layout") dv.props.Document.deiconifyLayout = layoutKey.replace("layout_", ""); } else { const deiconifyLayout = Cast(dv.props.Document.deiconifyLayout, "string", null); dv.setCustomView(deiconifyLayout ? true : false, deiconifyLayout); @@ -274,6 +274,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> } }); } + SelectionManager.DeselectAll(); } @action diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index c14d11cce..1fb3dcb36 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -902,7 +902,7 @@ export class DocumentView extends DocComponent(Docu const showTitle = StrCast(this.getLayoutPropStr("showTitle")); const showTitleHover = StrCast(this.getLayoutPropStr("showTitleHover")); const showCaption = this.getLayoutPropStr("showCaption"); - const showTextTitle = showTitle && StrCast(this.layoutDoc.layout).indexOf("FormattedTextBox") !== -1 ? showTitle : undefined; + const showTextTitle = showTitle && (StrCast(this.layoutDoc.layout).indexOf("PresBox") !== -1 || StrCast(this.layoutDoc.layout).indexOf("FormattedTextBox") !== -1) ? showTitle : undefined; const searchHighlight = (!this.Document.searchFields ? (null) :
{this.Document.searchFields} diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index 9b4844b19..862557302 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -784,8 +784,10 @@ export namespace Doc { export function setNativeView(doc: any) { const prevLayout = StrCast(doc.layoutKey).split("_")[1]; + const deiconify = prevLayout === "icon" && StrCast(doc.deiconifyLayout) ? "layout_" + StrCast(doc.deiconifyLayout) : ""; + doc.deiconifyLayout = undefined; if (StrCast(doc.title).endsWith("_" + prevLayout)) doc.title = StrCast(doc.title).replace("_" + prevLayout, ""); - doc.layoutKey = "layout"; + doc.layoutKey = deiconify || "layout"; } } diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index a6dd809f4..a4af46a63 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -17,6 +17,7 @@ import { InkingControl } from "../../../client/views/InkingControl"; import { CollectionViewType } from "../../../client/views/collections/CollectionView"; import { makeTemplate } from "../../../client/util/DropConverter"; import { RichTextField } from "../../../new_fields/RichTextField"; +import { PrefetchProxy } from "../../../new_fields/Proxy"; export class CurrentUserUtils { private static curr_id: string; @@ -47,17 +48,19 @@ export class CurrentUserUtils { // setup the "creator" buttons for the sidebar-- eg. the default set of draggable document creation tools static setupCreatorButtons(doc: Doc, buttons?: string[]) { const notes = CurrentUserUtils.setupNoteTypes(doc); + const emptyPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, showTitle: "title", boxShadow: "0 0" }); + const emptyCollection = Docs.Create.FreeformDocument([], { _nativeWidth: undefined, _nativeHeight: undefined, _LODdisable: true, _width: 150, _height: 100, title: "freeform" }); doc.noteTypes = Docs.Create.TreeDocument(notes, { title: "Note Types", _height: 75 }); doc.activePen = doc; const docProtoData: { title: string, icon: string, drag?: string, ignoreClick?: boolean, click?: string, ischecked?: string, activePen?: Doc, backgroundColor?: string, dragFactory?: Doc }[] = [ - { title: "collection", icon: "folder", ignoreClick: true, drag: 'Docs.Create.FreeformDocument([], { _nativeWidth: undefined, _nativeHeight: undefined, _LODdisable: true, _width: 150, _height: 100, title: "freeform" })' }, + { title: "collection", icon: "folder", click: 'openOnRight(getCopy(this.dragFactory))', drag: 'getCopy(this.dragFactory, true)', dragFactory: emptyCollection }, { title: "preview", icon: "expand", ignoreClick: true, drag: 'Docs.Create.DocumentDocument(ComputedField.MakeFunction("selectedDocs(this,true,[_last_])?.[0]"), { _width: 250, _height: 250, title: "container" })' }, { title: "todo item", icon: "check", ignoreClick: true, drag: 'getCopy(this.dragFactory, true)', dragFactory: notes[notes.length - 1] }, { title: "web page", icon: "globe-asia", ignoreClick: true, drag: 'Docs.Create.WebDocument("https://en.wikipedia.org/wiki/Hedgehog", {_width: 300, _height: 300, title: "New Webpage" })' }, { title: "cat image", icon: "cat", ignoreClick: true, drag: 'Docs.Create.ImageDocument("https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg", { _width: 200, title: "an image of a cat" })' }, { title: "record", icon: "microphone", ignoreClick: true, drag: `Docs.Create.AudioDocument("${nullAudio}", { _width: 200, title: "ready to record audio" })` }, { title: "clickable button", icon: "bolt", ignoreClick: true, drag: 'Docs.Create.ButtonDocument({ _width: 150, _height: 50, title: "Button" })' }, - { title: "presentation", icon: "tv", ignoreClick: true, drag: `Doc.UserDoc().curPresentation = Docs.Create.PresDocument(new List(), { _width: 200, _height: 500, _xMargin:5, _viewType: ${CollectionViewType.Stacking}, title: "a presentation trail" })` }, + { title: "presentation", icon: "tv", click: 'openOnRight(Doc.UserDoc().curPresentation = getCopy(this.dragFactory))', drag: `Doc.UserDoc().curPresentation = getCopy(this.dragFactory,true)`, dragFactory: emptyPresentation }, { title: "import folder", icon: "cloud-upload-alt", ignoreClick: true, drag: 'Docs.Create.DirectoryImportDocument({ title: "Directory Import", _width: 400, _height: 400 })' }, { title: "mobile view", icon: "phone", ignoreClick: true, drag: 'Doc.UserDoc().activeMobile' }, { title: "use pen", icon: "pen-nib", click: 'activatePen(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this,2, this.backgroundColor)', backgroundColor: "blue", ischecked: `sameDocs(this.activePen.pen, this)`, activePen: doc }, @@ -240,7 +243,7 @@ export class CurrentUserUtils { const iconDoc = Docs.Create.TextDocument("", { title: "icon", _width: 150, _height: 30, onClick: ScriptField.MakeScript("setNativeView(this)") }); Doc.GetProto(iconDoc).data = new RichTextField('{"doc":{"type":"doc","content":[{"type":"paragraph","attrs":{"align":null,"color":null,"id":null,"indent":null,"inset":null,"lineSpacing":null,"paddingBottom":null,"paddingTop":null},"content":[{"type":"dashField","attrs":{"fieldKey":"title","docid":""}}]}]},"selection":{"type":"text","anchor":2,"head":2},"storedMarks":[]}', ""); doc.isTemplateDoc = makeTemplate(iconDoc); - doc.iconView = iconDoc; + doc.iconView = new PrefetchProxy(iconDoc); doc.undoBtn = Docs.Create.FontIconDocument( { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, _dropAction: "alias", onClick: ScriptField.MakeScript("undo()"), removeDropProperties: new List(["dropAction"]), title: "undo button", icon: "undo-alt" }); @@ -266,7 +269,7 @@ export class CurrentUserUtils { // the initial presentation Doc to use static setupDefaultPresentation(doc: Doc) { - doc.curPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, boxShadow: "0 0" }); + doc.curPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, showTitle: "title", boxShadow: "0 0" }); } static setupMobileUploads(doc: Doc) { -- cgit v1.2.3-70-g09d2 From ab95c12485c26e5e0e6dc48cef8abd63a9c1fb56 Mon Sep 17 00:00:00 2001 From: bob Date: Wed, 5 Feb 2020 15:05:32 -0500 Subject: several layout fixes for row/col stuff. fixes to icons. added buttons for buxton app. made PresBox not search for its own contents when following a link --- src/client/util/DocumentManager.ts | 4 +- src/client/views/MainView.tsx | 4 +- .../views/collections/CollectionDockingView.tsx | 4 +- src/client/views/collections/CollectionSubView.tsx | 6 ++- .../views/collections/CollectionTimeView.tsx | 2 +- .../views/collections/CollectionTreeView.tsx | 47 +++++++++++++++------- .../collectionFreeForm/CollectionFreeFormView.tsx | 2 +- .../CollectionMulticolumnView.tsx | 5 +-- .../CollectionMultirowView.tsx | 4 +- src/client/views/nodes/DocumentView.tsx | 21 +++++----- .../authentication/models/current_user_utils.ts | 9 ++--- 11 files changed, 67 insertions(+), 41 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/util/DocumentManager.ts b/src/client/util/DocumentManager.ts index 9fff8faa7..60bb25272 100644 --- a/src/client/util/DocumentManager.ts +++ b/src/client/util/DocumentManager.ts @@ -93,9 +93,9 @@ export class DocumentManager { const toReturn: DocumentView[] = []; DocumentManager.Instance.DocumentViews.map(view => - view.props.Document === toFind && toReturn.push(view)); + view.props.Document.presBox === undefined && view.props.Document === toFind && toReturn.push(view)); DocumentManager.Instance.DocumentViews.map(view => - view.props.Document !== toFind && Doc.AreProtosEqual(view.props.Document, toFind) && toReturn.push(view)); + view.props.Document.presBox === undefined && view.props.Document !== toFind && Doc.AreProtosEqual(view.props.Document, toFind) && toReturn.push(view)); return toReturn; } diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 0cc374cee..a839f9fd2 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -1,6 +1,6 @@ import { library } from '@fortawesome/fontawesome-svg-core'; import { - faStickyNote, faArrowDown, faBullseye, faFilter, faArrowUp, faBolt, faCaretUp, faCat, faCheck, faChevronRight, faClone, faCloudUploadAlt, faCommentAlt, faCut, faEllipsisV, faExclamation, faFilePdf, faFilm, faFont, faGlobeAsia, faLongArrowAltRight, + faFileAlt, faStickyNote, faArrowDown, faBullseye, faFilter, faArrowUp, faBolt, faCaretUp, faCat, faCheck, faChevronRight, faClone, faCloudUploadAlt, faCommentAlt, faCut, faEllipsisV, faExclamation, faFilePdf, faFilm, faFont, faGlobeAsia, faLongArrowAltRight, faMusic, faObjectGroup, faPause, faMousePointer, faPenNib, faFileAudio, faPen, faEraser, faPlay, faPortrait, faRedoAlt, faThumbtack, faTree, faTv, faUndoAlt, faHighlighter, faMicrophone, faCompressArrowsAlt, faPhone, faStamp, faClipboard } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; @@ -101,6 +101,8 @@ export class MainView extends React.Component { } } + library.add(faFileAlt); + library.add(faStickyNote); library.add(faFont); library.add(faExclamation); library.add(faPortrait); diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 861a63503..9c67d8041 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -468,7 +468,9 @@ export class CollectionDockingView extends React.Component { e.preventDefault(); e.stopPropagation(); - DragManager.StartDocumentDrag([dragSpan], new DragManager.DocumentDragData([doc]), e.clientX, e.clientY); + const dragData = new DragManager.DocumentDragData([doc]); + dragData.dropAction = doc._dropAction; + DragManager.StartDocumentDrag([dragSpan], dragData, e.clientX, e.clientY); }}> , dragSpan); diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index a2700e75a..731b5b01d 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -128,11 +128,15 @@ export function CollectionSubView(schemaCtor: (doc: Doc) => T) { const filteredDocs = docFilters.length ? viewedDocs.filter(d => { for (const key of Object.keys(clusters)) { const cluster = clusters[key]; + const satisfiesFacetx = !Object.keys(cluster).some((inner) => { + const modifier = cluster[inner]; + return ((modifier === "x") === Doc.matchFieldValue(d, key, inner)); + }); const satisfiesFacet = Object.keys(cluster).some(inner => { const modifier = cluster[inner]; return (modifier === "x") !== Doc.matchFieldValue(d, key, inner); }); - if (!satisfiesFacet) { + if (!satisfiesFacet || !satisfiesFacetx) { return false; } } diff --git a/src/client/views/collections/CollectionTimeView.tsx b/src/client/views/collections/CollectionTimeView.tsx index 264423d72..896fb74f0 100644 --- a/src/client/views/collections/CollectionTimeView.tsx +++ b/src/client/views/collections/CollectionTimeView.tsx @@ -33,7 +33,7 @@ export class CollectionTimeView extends CollectionSubView(doc => doc) { this.props.Document.excludeFields = new List(["_facetCollection", "_docFilter"]); const scriptText = "setDocFilter(containingTreeView.target, heading, this.title, checked)"; - const childText = "const alias = getAlias(this); Doc.ApplyTemplateTo(containingCollection.childDetailed, alias, 'layout_detailed'); useRightSplit(alias, shiftKey); "; + const childText = "const alias = getAlias(this); Doc.ApplyTemplateTo(containingCollection.childDetailed, alias, 'layout_detailView'); alias._dropAction='alias'; alias.removeDropProperties=new List(['dropAction']); useRightSplit(alias, shiftKey); "; facetCollection.onCheckedClick = ScriptField.MakeScript(scriptText, { this: Doc.name, heading: "boolean", checked: "boolean", containingTreeView: Doc.name }); this.props.Document.onChildClick = ScriptField.MakeScript(childText, { this: Doc.name, heading: "boolean", containingCollection: Doc.name, shiftKey: "boolean" }); this.props.Document._facetCollection = facetCollection; diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index 9e3fb1d67..19900c48b 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -640,27 +640,46 @@ export class CollectionTreeView extends CollectionSubView(Document) { d.captions = undefined; }); }); - const { TextDocument, ImageDocument, CarouselDocument } = Docs.Create; + const { TextDocument, ImageDocument, CarouselDocument, TreeDocument } = Docs.Create; const { Document } = this.props; const fallbackImg = "http://www.cs.brown.edu/~bcz/face.gif"; - const detailedTemplate = `{ "doc": { "type": "doc", "content": [ { "type": "paragraph", "content": [ { "type": "dashField", "attrs": { "fieldKey": "short_description" } } ] }, { "type": "paragraph", "content": [ { "type": "dashField", "attrs": { "fieldKey": "year" } } ] }, { "type": "paragraph", "content": [ { "type": "dashField", "attrs": { "fieldKey": "company" } } ] } ] }, "selection":{"type":"text","anchor":1,"head":1},"storedMarks":[] }`; + const detailedTemplate = `{ "doc": { "type": "doc", "content": [ { "type": "paragraph", "content": [ { "type": "dashField", "attrs": { "fieldKey": "year" } } ] }, { "type": "paragraph", "content": [ { "type": "dashField", "attrs": { "fieldKey": "company" } } ] } ] }, "selection":{"type":"text","anchor":1,"head":1},"storedMarks":[] }`; const textDoc = TextDocument("", { title: "details", _autoHeight: true }); - const detailedLayout = Docs.Create.StackingDocument([ + const detailView = Docs.Create.StackingDocument([ CarouselDocument([], { title: "data", _height: 350, _itemIndex: 0, backgroundColor: "#9b9b9b3F" }), textDoc, - ], { _chromeStatus: "disabled", title: "detailed layout stack" }); - textDoc.data = new RichTextField(detailedTemplate, "short_description year company"); - detailedLayout.isTemplateDoc = makeTemplate(detailedLayout); - - const cardLayout = ImageDocument(fallbackImg, { title: "cardLayout", isTemplateDoc: true, isTemplateForField: "hero", }); // this acts like a template doc and a template field ... a little weird, but seems to work? - cardLayout.proto!.layout = ImageBox.LayoutString("hero"); - cardLayout.showTitle = "title"; - cardLayout.showTitleHover = "titlehover"; - - Document.childLayout = cardLayout; - Document.childDetailed = detailedLayout; + TextDocument("", { title: "short_description", _autoHeight: true }), + TreeDocument([], { title: "narratives", _height: 75, treeViewHideTitle: true }) + ], { _chromeStatus: "disabled", _width: 300, _height: 300, _autoHeight: true, title: "detailView" }); + textDoc.data = new RichTextField(detailedTemplate, "year company"); + detailView.isTemplateDoc = makeTemplate(detailView); + + + const heroView = ImageDocument(fallbackImg, { title: "heroView", isTemplateDoc: true, isTemplateForField: "hero", }); // this acts like a template doc and a template field ... a little weird, but seems to work? + heroView.proto!.layout = ImageBox.LayoutString("hero"); + heroView.showTitle = "title"; + heroView.showTitleHover = "titlehover"; + heroView._dropAction = "alias"; + heroView.removeDropProperties = new List(["dropAction"]); + + Doc.AddDocToList(CurrentUserUtils.UserDocument.expandingButtons as Doc, "data", + Docs.Create.FontIconDocument({ + _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, _dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), + dragFactory: heroView, removeDropProperties: new List(["dropAction"]), title: "hero view", icon: "portrait" + })); + + Doc.AddDocToList(CurrentUserUtils.UserDocument.expandingButtons as Doc, "data", + Docs.Create.FontIconDocument({ + _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, _dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), + dragFactory: detailView, removeDropProperties: new List(["dropAction"]), title: "detail view", icon: "file-alt" + })); + + + Document.childLayout = heroView; + Document.childDetailed = detailView; Document._viewType = CollectionViewType.Time; + Document._forceActive = true; Document.pivotField = "company"; } }); diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 6b81eba7d..54c45e43a 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -434,7 +434,7 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { let y = this.Document._panY || 0; const docs = this.childLayoutPairs.filter(pair => pair.layout instanceof Doc && !pair.layout.isMinimized).map(pair => pair.layout); const [dx, dy] = this.getTransform().transformDirection(e.clientX - this._lastX, e.clientY - this._lastY); - if (!this.isAnnotationOverlay && docs.length) { + if (!this.isAnnotationOverlay && docs.length && this.childDataProvider(docs[0])) { PDFMenu.Instance.fadeOut(true); const minx = this.childDataProvider(docs[0]).x;//docs.length ? NumCast(docs[0].x) : 0; const miny = this.childDataProvider(docs[0]).y;//docs.length ? NumCast(docs[0].y) : 0; diff --git a/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx b/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx index 92b908ab6..7d8de0db4 100644 --- a/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx +++ b/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx @@ -5,7 +5,6 @@ import { Doc } from '../../../../new_fields/Doc'; import { documentSchema } from '../../../../new_fields/documentSchemas'; import { makeInterface } from '../../../../new_fields/Schema'; import { BoolCast, NumCast, ScriptCast, StrCast } from '../../../../new_fields/Types'; -import { Utils } from '../../../../Utils'; import { DragManager } from '../../../util/DragManager'; import { Transform } from '../../../util/Transform'; import { undoBatch } from '../../../util/UndoManager'; @@ -119,7 +118,7 @@ export class CollectionMulticolumnView extends CollectionSubView(MulticolumnDocu private get totalRatioAllocation(): number | undefined { const layoutInfoLen = this.resolvedLayoutInformation.widthSpecifiers.length; if (layoutInfoLen > 0 && this.totalFixedAllocation !== undefined) { - return this.props.PanelWidth() - (this.totalFixedAllocation + resizerWidth * (layoutInfoLen - 1)); + return this.props.PanelWidth() - (this.totalFixedAllocation + resizerWidth * (layoutInfoLen - 1)) - 2 * NumCast(this.props.Document._xMargin); } } @@ -228,7 +227,7 @@ export class CollectionMulticolumnView extends CollectionSubView(MulticolumnDocu for (let i = 0; i < childLayoutPairs.length; i++) { const { layout } = childLayoutPairs[i]; const dxf = () => this.lookupIndividualTransform(layout).translate(-NumCast(Document._xMargin), -NumCast(Document._yMargin)); - const width = () => this.lookupPixels(layout) - 2 * NumCast(Document._xMargin); + const width = () => this.lookupPixels(layout); const height = () => PanelHeight() - 2 * NumCast(Document._yMargin) - (BoolCast(Document.showWidthLabels) ? 20 : 0); collector.push(
0 && this.totalFixedAllocation !== undefined) { - return this.props.PanelHeight() - (this.totalFixedAllocation + resizerHeight * (layoutInfoLen - 1)); + return this.props.PanelHeight() - (this.totalFixedAllocation + resizerHeight * (layoutInfoLen - 1)) - 2 * NumCast(this.props.Document._yMargin); } } @@ -228,7 +228,7 @@ export class CollectionMultirowView extends CollectionSubView(MultirowDocument) for (let i = 0; i < childLayoutPairs.length; i++) { const { layout } = childLayoutPairs[i]; const dxf = () => this.lookupIndividualTransform(layout).translate(-NumCast(Document._xMargin), -NumCast(Document._yMargin)); - const height = () => this.lookupPixels(layout) - 2 * NumCast(Document._yMargin); + const height = () => this.lookupPixels(layout); const width = () => PanelWidth() - 2 * NumCast(Document._xMargin) - (BoolCast(Document.showWidthLabels) ? 20 : 0); collector.push(
(Docu if (e.cancelBubble && this.active) { document.removeEventListener("pointermove", this.onPointerMove); // stop listening to pointerMove if something else has stopPropagated it (e.g., the MarqueeView) } - else if (!e.cancelBubble && (SelectionManager.IsSelected(this, true) || this.props.parentActive(true) || this.Document.onDragStart || this.Document.onClick) && !this.Document.lockedPosition && !this.Document.inOverlay) { + else if (!e.cancelBubble && (SelectionManager.IsSelected(this, true) || this.props.parentActive(true) || this.Document.onDragStart || this.onClickHandler) && !this.Document.lockedPosition && !this.Document.inOverlay) { if (Math.abs(this._downX - e.clientX) > 3 || Math.abs(this._downY - e.clientY) > 3) { - if (!e.altKey && (!this.topMost || this.Document.onDragStart || this.Document.onClick) && (e.buttons === 1 || InteractionUtils.IsType(e, InteractionUtils.TOUCHTYPE))) { + if (!e.altKey && (!this.topMost || this.Document.onDragStart || this.onClickHandler) && (e.buttons === 1 || InteractionUtils.IsType(e, InteractionUtils.TOUCHTYPE))) { document.removeEventListener("pointermove", this.onPointerMove); document.removeEventListener("pointerup", this.onPointerUp); this.startDragging(this._downX, this._downY, this.Document._dropAction ? this.Document._dropAction as any : e.ctrlKey || e.altKey ? "alias" : undefined, this._hitTemplateDrag); @@ -518,7 +518,7 @@ export class DocumentView extends DocComponent(Docu } @undoBatch - deleteClicked = (): void => { SelectionManager.DeselectAll(); this.props.removeDocument && this.props.removeDocument(this.props.Document); } + deleteClicked = (): void => { SelectionManager.DeselectAll(); this.props.removeDocument?.(this.props.Document); } static makeNativeViewClicked = (doc: Doc) => { undoBatch(() => Doc.setNativeView(doc))(); @@ -597,7 +597,7 @@ export class DocumentView extends DocComponent(Docu `Link from ${StrCast(de.complete.annoDragData.annotationDocument.title)}`); } if (de.complete.docDragData && de.complete.docDragData.applyAsTemplate) { - Doc.ApplyTemplateTo(de.complete.docDragData.draggedDocuments[0], this.props.Document, "layout_custom"); + Doc.ApplyTemplateTo(de.complete.docDragData.draggedDocuments[0], this.props.Document, "layout_custom", undefined); e.stopPropagation(); } if (de.complete.linkDragData) { @@ -656,12 +656,13 @@ export class DocumentView extends DocComponent(Docu if (custom) { DocumentView.makeNativeViewClicked(this.props.Document); - let foundLayout: Opt = Cast(Doc.UserDoc().iconView, Doc, null); - !foundLayout && DocListCast(Cast(CurrentUserUtils.UserDocument.expandingButtons, Doc, null)?.data)?.map(btnDoc => { - if (StrCast(Cast(btnDoc?.dragFactory, Doc, null)?.title) === layout) { - foundLayout = btnDoc.dragFactory as Doc; - } - }) + let foundLayout: Opt; + DocListCast(Cast(Doc.UserDoc().expandingButtons, Doc, null)?.data)?.concat([Cast(Doc.UserDoc().iconView, Doc, null)]). + map(btnDoc => (btnDoc.dragFactory as Doc) || btnDoc).filter(doc => doc.isTemplateDoc).forEach(tempDoc => { + if (StrCast(tempDoc.title) === layout) { + foundLayout = tempDoc; + } + }) DocumentView. makeCustomViewClicked(this.props.Document, this.props.DataDoc, Docs.Create.StackingDocument, layout, foundLayout); } else { diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index a4af46a63..74db511df 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -53,14 +53,14 @@ export class CurrentUserUtils { doc.noteTypes = Docs.Create.TreeDocument(notes, { title: "Note Types", _height: 75 }); doc.activePen = doc; const docProtoData: { title: string, icon: string, drag?: string, ignoreClick?: boolean, click?: string, ischecked?: string, activePen?: Doc, backgroundColor?: string, dragFactory?: Doc }[] = [ - { title: "collection", icon: "folder", click: 'openOnRight(getCopy(this.dragFactory))', drag: 'getCopy(this.dragFactory, true)', dragFactory: emptyCollection }, + { title: "collection", icon: "folder", click: 'openOnRight(getCopy(this.dragFactory, true))', drag: 'getCopy(this.dragFactory, true)', dragFactory: emptyCollection }, { title: "preview", icon: "expand", ignoreClick: true, drag: 'Docs.Create.DocumentDocument(ComputedField.MakeFunction("selectedDocs(this,true,[_last_])?.[0]"), { _width: 250, _height: 250, title: "container" })' }, { title: "todo item", icon: "check", ignoreClick: true, drag: 'getCopy(this.dragFactory, true)', dragFactory: notes[notes.length - 1] }, { title: "web page", icon: "globe-asia", ignoreClick: true, drag: 'Docs.Create.WebDocument("https://en.wikipedia.org/wiki/Hedgehog", {_width: 300, _height: 300, title: "New Webpage" })' }, { title: "cat image", icon: "cat", ignoreClick: true, drag: 'Docs.Create.ImageDocument("https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg", { _width: 200, title: "an image of a cat" })' }, { title: "record", icon: "microphone", ignoreClick: true, drag: `Docs.Create.AudioDocument("${nullAudio}", { _width: 200, title: "ready to record audio" })` }, { title: "clickable button", icon: "bolt", ignoreClick: true, drag: 'Docs.Create.ButtonDocument({ _width: 150, _height: 50, title: "Button" })' }, - { title: "presentation", icon: "tv", click: 'openOnRight(Doc.UserDoc().curPresentation = getCopy(this.dragFactory))', drag: `Doc.UserDoc().curPresentation = getCopy(this.dragFactory,true)`, dragFactory: emptyPresentation }, + { title: "presentation", icon: "tv", click: 'openOnRight(Doc.UserDoc().curPresentation = getCopy(this.dragFactory, true))', drag: `Doc.UserDoc().curPresentation = getCopy(this.dragFactory,true)`, dragFactory: emptyPresentation }, { title: "import folder", icon: "cloud-upload-alt", ignoreClick: true, drag: 'Docs.Create.DirectoryImportDocument({ title: "Directory Import", _width: 400, _height: 400 })' }, { title: "mobile view", icon: "phone", ignoreClick: true, drag: 'Doc.UserDoc().activeMobile' }, { title: "use pen", icon: "pen-nib", click: 'activatePen(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this,2, this.backgroundColor)', backgroundColor: "blue", ischecked: `sameDocs(this.activePen.pen, this)`, activePen: doc }, @@ -240,7 +240,7 @@ export class CurrentUserUtils { { _width: 400, _height: 300, title: "slide", _chromeStatus: "disabled", _autoHeight: true }); slideTemplate.isTemplateDoc = makeTemplate(slideTemplate); - const iconDoc = Docs.Create.TextDocument("", { title: "icon", _width: 150, _height: 30, onClick: ScriptField.MakeScript("setNativeView(this)") }); + const iconDoc = Docs.Create.TextDocument("", { title: "icon", _width: 150, _height: 30, isTemplateDoc: true, onClick: ScriptField.MakeScript("setNativeView(this)") }); Doc.GetProto(iconDoc).data = new RichTextField('{"doc":{"type":"doc","content":[{"type":"paragraph","attrs":{"align":null,"color":null,"id":null,"indent":null,"inset":null,"lineSpacing":null,"paddingBottom":null,"paddingTop":null},"content":[{"type":"dashField","attrs":{"fieldKey":"title","docid":""}}]}]},"selection":{"type":"text","anchor":2,"head":2},"storedMarks":[]}', ""); doc.isTemplateDoc = makeTemplate(iconDoc); doc.iconView = new PrefetchProxy(iconDoc); @@ -250,8 +250,7 @@ export class CurrentUserUtils { doc.redoBtn = Docs.Create.FontIconDocument( { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, _dropAction: "alias", onClick: ScriptField.MakeScript("redo()"), removeDropProperties: new List(["dropAction"]), title: "redo button", icon: "redo-alt" }); doc.slidesBtn = Docs.Create.FontIconDocument( - { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, _dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: slideTemplate, removeDropProperties: new List(["dropAction"]), title: "slide button", icon: "sticky-note" }); - + { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, _dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: slideTemplate, removeDropProperties: new List(["dropAction"]), title: "presentation slide", icon: "sticky-note" }); doc.expandingButtons = Docs.Create.LinearDocument([doc.undoBtn as Doc, doc.redoBtn as Doc, doc.slidesBtn as Doc], { title: "expanding buttons", _gridGap: 5, _xMargin: 5, _yMargin: 5, _height: 42, _width: 100, boxShadow: "0 0", backgroundColor: "black", preventTreeViewOpen: true, forceActive: true, lockedPosition: true, -- cgit v1.2.3-70-g09d2 From 714e66d2916971b5b023ba33c20b8794c1d536e2 Mon Sep 17 00:00:00 2001 From: bob Date: Thu, 6 Feb 2020 09:25:50 -0500 Subject: fixed unsetting of dropAction in buxton layouts. --- src/client/documents/Documents.ts | 6 +++--- src/client/util/DragManager.ts | 7 +++++-- src/client/views/collections/CollectionDockingView.tsx | 2 +- src/client/views/collections/CollectionTimeView.tsx | 2 +- src/client/views/collections/CollectionTreeView.tsx | 9 ++++----- src/client/views/nodes/DocumentView.tsx | 4 ++-- src/new_fields/documentSchemas.ts | 2 +- src/server/authentication/models/current_user_utils.ts | 16 ++++++++-------- 8 files changed, 25 insertions(+), 23 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 17570fcb5..64dc0d8b7 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -67,7 +67,7 @@ export interface DocumentOptions { _fitWidth?: boolean; _fitToBox?: boolean; // whether a freeformview should zoom/scale to create a shrinkwrapped view of its contents _LODdisable?: boolean; - _dropAction?: dropActionType; + dropAction?: dropActionType; _chromeStatus?: string; _viewType?: number; _gridGap?: number; // gap between items in masonry view @@ -340,7 +340,7 @@ export namespace Docs { */ export namespace Create { - const delegateKeys = ["x", "y", "layoutKey", "_width", "_height", "_panX", "_panY", "_viewType", "_nativeWidth", "_nativeHeight", "_dropAction", "_annotationOn", + const delegateKeys = ["x", "y", "layoutKey", "_width", "_height", "_panX", "_panY", "_viewType", "_nativeWidth", "_nativeHeight", "dropAction", "_annotationOn", "_chromeStatus", "_forceActive", "_autoHeight", "_fitWidth", "_LODdisable", "_itemIndex", "_showSidebar", "showTitle"]; /** @@ -745,7 +745,7 @@ export namespace Docs { } if (type.indexOf("excel") !== -1) { ctor = Docs.Create.DBDocument; - options._dropAction = "copy"; + options.dropAction = "copy"; } if (type.indexOf("html") !== -1) { if (path.includes(window.location.hostname)) { diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index c05a2de96..b0dd90947 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -15,7 +15,7 @@ import { listSpec } from "../../new_fields/Schema"; import { Scripting } from "./Scripting"; import { convertDropDataToButtons } from "./DropConverter"; -export type dropActionType = "alias" | "copy" | undefined; +export type dropActionType = "alias" | "copy" | "move" | undefined; export function SetupDrag( _reference: React.RefObject, docFunc: () => Doc | Promise | undefined, @@ -197,7 +197,10 @@ export namespace DragManager { dragData.userDropAction === "copy" || (!dragData.userDropAction && dragData.dropAction === "copy") ? Doc.MakeCopy(d, true) : d) ); e.docDragData?.droppedDocuments.forEach((drop: Doc, i: number) => - Cast(dragData.draggedDocuments[i].removeDropProperties, listSpec("string"), []).map(prop => drop[prop] = undefined)); + Cast(dragData.draggedDocuments[i].removeDropProperties, listSpec("string"), []).map(prop => { + drop[prop] = "move"; + }) + ); }; dragData.draggedDocuments.map(d => d.dragFactory); // does this help? trying to make sure the dragFactory Doc is loaded StartDrag(eles, dragData, downX, downY, options, finishDrag); diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 9c67d8041..2478aaecd 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -469,7 +469,7 @@ export class CollectionDockingView extends React.Component diff --git a/src/client/views/collections/CollectionTimeView.tsx b/src/client/views/collections/CollectionTimeView.tsx index 896fb74f0..ae5a3c7dc 100644 --- a/src/client/views/collections/CollectionTimeView.tsx +++ b/src/client/views/collections/CollectionTimeView.tsx @@ -33,7 +33,7 @@ export class CollectionTimeView extends CollectionSubView(doc => doc) { this.props.Document.excludeFields = new List(["_facetCollection", "_docFilter"]); const scriptText = "setDocFilter(containingTreeView.target, heading, this.title, checked)"; - const childText = "const alias = getAlias(this); Doc.ApplyTemplateTo(containingCollection.childDetailed, alias, 'layout_detailView'); alias._dropAction='alias'; alias.removeDropProperties=new List(['dropAction']); useRightSplit(alias, shiftKey); "; + const childText = "const alias = getAlias(this); Doc.ApplyTemplateTo(containingCollection.childDetailed, alias, 'layout_detailView'); alias.dropAction='alias'; alias.removeDropProperties=new List(['dropAction']); useRightSplit(alias, shiftKey); "; facetCollection.onCheckedClick = ScriptField.MakeScript(scriptText, { this: Doc.name, heading: "boolean", checked: "boolean", containingTreeView: Doc.name }); this.props.Document.onChildClick = ScriptField.MakeScript(childText, { this: Doc.name, heading: "boolean", containingCollection: Doc.name, shiftKey: "boolean" }); this.props.Document._facetCollection = facetCollection; diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index 19900c48b..f44c7a7b0 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -660,18 +660,16 @@ export class CollectionTreeView extends CollectionSubView(Document) { heroView.proto!.layout = ImageBox.LayoutString("hero"); heroView.showTitle = "title"; heroView.showTitleHover = "titlehover"; - heroView._dropAction = "alias"; - heroView.removeDropProperties = new List(["dropAction"]); Doc.AddDocToList(CurrentUserUtils.UserDocument.expandingButtons as Doc, "data", Docs.Create.FontIconDocument({ - _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, _dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), + _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: heroView, removeDropProperties: new List(["dropAction"]), title: "hero view", icon: "portrait" })); Doc.AddDocToList(CurrentUserUtils.UserDocument.expandingButtons as Doc, "data", Docs.Create.FontIconDocument({ - _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, _dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), + _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: detailView, removeDropProperties: new List(["dropAction"]), title: "detail view", icon: "file-alt" })); @@ -680,6 +678,7 @@ export class CollectionTreeView extends CollectionSubView(Document) { Document.childDetailed = detailView; Document._viewType = CollectionViewType.Time; Document._forceActive = true; + Document.childDropAction = "alias"; Document.pivotField = "company"; } }); @@ -704,7 +703,7 @@ export class CollectionTreeView extends CollectionSubView(Document) { } render() { - const dropAction = StrCast(this.props.Document._dropAction) as dropActionType; + const dropAction = StrCast(this.props.Document.dropAction) as dropActionType; const addDoc = (doc: Doc, relativeTo?: Doc, before?: boolean) => Doc.AddDocToList(this.props.Document, this.props.fieldKey, doc, relativeTo, before, false, false, false); const moveDoc = (d: Doc, target: Doc | undefined, addDoc: (doc: Doc) => boolean) => this.props.moveDocument(d, target, addDoc); return !this.childDocs ? (null) : ( diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index c04402360..f9d9e7212 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -348,7 +348,7 @@ export class DocumentView extends DocComponent(Docu if (Math.abs(this._downX - touch.clientX) > 3 || Math.abs(this._downY - touch.clientY) > 3) { if (!e.altKey && (!this.topMost || this.Document.onDragStart || this.Document.onClick)) { this.cleanUpInteractions(); - this.startDragging(this._downX, this._downY, this.Document._dropAction ? this.Document._dropAction as any : e.ctrlKey || e.altKey ? "alias" : undefined, this._hitTemplateDrag); + this.startDragging(this._downX, this._downY, this.Document.dropAction ? this.Document.dropAction as any : e.ctrlKey || e.altKey ? "alias" : undefined, this._hitTemplateDrag); } } e.stopPropagation(); // doesn't actually stop propagation since all our listeners are listening to events on 'document' however it does mark the event as cancelBubble=true which we test for in the move event handlers @@ -489,7 +489,7 @@ export class DocumentView extends DocComponent(Docu if (!e.altKey && (!this.topMost || this.Document.onDragStart || this.onClickHandler) && (e.buttons === 1 || InteractionUtils.IsType(e, InteractionUtils.TOUCHTYPE))) { document.removeEventListener("pointermove", this.onPointerMove); document.removeEventListener("pointerup", this.onPointerUp); - this.startDragging(this._downX, this._downY, this.Document._dropAction ? this.Document._dropAction as any : e.ctrlKey || e.altKey ? "alias" : undefined, this._hitTemplateDrag); + this.startDragging(this._downX, this._downY, this.props.ContainingCollectionDoc?.childDropAction ? this.props.ContainingCollectionDoc?.childDropAction : this.Document.dropAction ? this.Document.dropAction as any : e.ctrlKey || e.altKey ? "alias" : undefined, this._hitTemplateDrag); } } e.stopPropagation(); // doesn't actually stop propagation since all our listeners are listening to events on 'document' however it does mark the event as cancelBubble=true which we test for in the move event handlers diff --git a/src/new_fields/documentSchemas.ts b/src/new_fields/documentSchemas.ts index 0b3bd6338..1aed5c242 100644 --- a/src/new_fields/documentSchemas.ts +++ b/src/new_fields/documentSchemas.ts @@ -8,7 +8,7 @@ export const documentSchema = createSchema({ layoutKey: "string", // holds the field key for the field that actually holds the current lyoat layout_custom: Doc, // used to hold a custom layout (there's nothing special about this field .. any field could hold a custom layout that can be selected by setting 'layoutKey') title: "string", // document title (can be on either data document or layout) - _dropAction: "string", // override specifying what should happen when this document is dropped (can be "alias" or "copy") + dropAction: "string", // override specifying what should happen when this document is dropped (can be "alias" or "copy") _nativeWidth: "number", // native width of document which determines how much document contents are scaled when the document's width is set _nativeHeight: "number", // " _width: "number", // width of document in its container's coordinate system diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 74db511df..b23ab5e49 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -71,7 +71,7 @@ export class CurrentUserUtils { { title: "use drag", icon: "mouse-pointer", click: 'deactivateInk();this.activePen.pen = this;', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "white", activePen: doc }, ]; return docProtoData.filter(d => !buttons || !buttons.includes(d.title)).map(data => Docs.Create.FontIconDocument({ - _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, _dropAction: data.click ? "copy" : undefined, title: data.title, icon: data.icon, ignoreClick: data.ignoreClick, + _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: data.click ? "copy" : undefined, title: data.title, icon: data.icon, ignoreClick: data.ignoreClick, onDragStart: data.drag ? ScriptField.MakeFunction(data.drag) : undefined, onClick: data.click ? ScriptField.MakeScript(data.click) : undefined, ischecked: data.ischecked ? ComputedField.MakeFunction(data.ischecked) : undefined, activePen: data.activePen, backgroundColor: data.backgroundColor, removeDropProperties: new List(["dropAction"]), dragFactory: data.dragFactory, @@ -109,7 +109,7 @@ export class CurrentUserUtils { { title: "use drag", icon: "mouse-pointer", click: 'deactivateInk();this.activePen.pen = this;', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "white", activePen: doc }, ]; return docProtoData.filter(d => !buttons || !buttons.includes(d.title)).map(data => Docs.Create.FontIconDocument({ - _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, _dropAction: data.click ? "copy" : undefined, title: data.title, icon: data.icon, ignoreClick: data.ignoreClick, + _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: data.click ? "copy" : undefined, title: data.title, icon: data.icon, ignoreClick: data.ignoreClick, onDragStart: data.drag ? ScriptField.MakeFunction(data.drag) : undefined, onClick: data.click ? ScriptField.MakeScript(data.click) : undefined, ischecked: data.ischecked ? ComputedField.MakeFunction(data.ischecked) : undefined, activePen: data.activePen, backgroundColor: data.backgroundColor, removeDropProperties: new List(["dropAction"]), dragFactory: data.dragFactory, @@ -125,7 +125,7 @@ export class CurrentUserUtils { { title: "ignore gestures", icon: "signature", pointerUp: "setToolglass('none')", pointerDown: "setToolglass('ignoregesture')", backgroundColor: "green", ischecked: `sameDocs(this.activePen.pen, this)`, activePen: doc }, ]; return docProtoData.map(data => Docs.Create.FontIconDocument({ - _nativeWidth: 10, _nativeHeight: 10, _width: 10, _height: 10, _dropAction: data.pointerDown ? "copy" : undefined, title: data.title, icon: data.icon, ignoreClick: data.ignoreClick, + _nativeWidth: 10, _nativeHeight: 10, _width: 10, _height: 10, dropAction: data.pointerDown ? "copy" : undefined, title: data.title, icon: data.icon, ignoreClick: data.ignoreClick, onDragStart: data.drag ? ScriptField.MakeFunction(data.drag) : undefined, clipboard: data.clipboard, onPointerUp: data.pointerUp ? ScriptField.MakeScript(data.pointerUp) : undefined, onPointerDown: data.pointerDown ? ScriptField.MakeScript(data.pointerDown) : undefined, @@ -158,7 +158,7 @@ export class CurrentUserUtils { }); // setup a color picker const color = Docs.Create.ColorDocument({ - title: "color picker", _width: 300, _dropAction: "alias", forceActive: true, removeDropProperties: new List(["dropAction", "forceActive"]) + title: "color picker", _width: 300, dropAction: "alias", forceActive: true, removeDropProperties: new List(["dropAction", "forceActive"]) }); return Docs.Create.ButtonDocument({ @@ -191,7 +191,7 @@ export class CurrentUserUtils { _width: 50, _height: 25, backgroundColor: "lightgrey", color: "rgb(34, 34, 34)", title: "Library", fontSize: 10, letterSpacing: "0px", textTransform: "unset", borderRounding: "5px 5px 0px 0px", boxShadow: "3px 3px 0px rgb(34, 34, 34)", sourcePanel: Docs.Create.TreeDocument([doc.workspaces as Doc, doc.documents as Doc, doc.recentlyClosed as Doc], { - title: "Library", _xMargin: 5, _yMargin: 5, _gridGap: 5, forceActive: true, _dropAction: "alias", lockedPosition: true, boxShadow: "0 0", + title: "Library", _xMargin: 5, _yMargin: 5, _gridGap: 5, forceActive: true, dropAction: "alias", lockedPosition: true, boxShadow: "0 0", }), targetContainer: sidebarContainer, onClick: ScriptField.MakeScript("this.targetContainer.proto = this.sourcePanel;") @@ -246,11 +246,11 @@ export class CurrentUserUtils { doc.iconView = new PrefetchProxy(iconDoc); doc.undoBtn = Docs.Create.FontIconDocument( - { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, _dropAction: "alias", onClick: ScriptField.MakeScript("undo()"), removeDropProperties: new List(["dropAction"]), title: "undo button", icon: "undo-alt" }); + { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onClick: ScriptField.MakeScript("undo()"), removeDropProperties: new List(["dropAction"]), title: "undo button", icon: "undo-alt" }); doc.redoBtn = Docs.Create.FontIconDocument( - { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, _dropAction: "alias", onClick: ScriptField.MakeScript("redo()"), removeDropProperties: new List(["dropAction"]), title: "redo button", icon: "redo-alt" }); + { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onClick: ScriptField.MakeScript("redo()"), removeDropProperties: new List(["dropAction"]), title: "redo button", icon: "redo-alt" }); doc.slidesBtn = Docs.Create.FontIconDocument( - { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, _dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: slideTemplate, removeDropProperties: new List(["dropAction"]), title: "presentation slide", icon: "sticky-note" }); + { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: slideTemplate, removeDropProperties: new List(["dropAction"]), title: "presentation slide", icon: "sticky-note" }); doc.expandingButtons = Docs.Create.LinearDocument([doc.undoBtn as Doc, doc.redoBtn as Doc, doc.slidesBtn as Doc], { title: "expanding buttons", _gridGap: 5, _xMargin: 5, _yMargin: 5, _height: 42, _width: 100, boxShadow: "0 0", backgroundColor: "black", preventTreeViewOpen: true, forceActive: true, lockedPosition: true, -- cgit v1.2.3-70-g09d2 From 061ed9215af59b8bc41cb3f3e8661687209341cd Mon Sep 17 00:00:00 2001 From: bob Date: Thu, 6 Feb 2020 18:33:07 -0500 Subject: quick fixes for pivot layout & pivoting down --- .../collectionFreeForm/CollectionFreeFormLayoutEngines.tsx | 6 +++--- .../views/collections/collectionFreeForm/CollectionFreeFormView.tsx | 4 ++-- src/server/authentication/models/current_user_utils.ts | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx index 4ef579f27..e354ad0af 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx @@ -192,7 +192,7 @@ export function computeTimelineLayout( childDocs: Doc[], childPairs: { layout: Doc, data?: Doc }[], panelDim: number[], - viewDefsToJSX: (views: any) => ViewDefResult[] + viewDefsToJSX: (views: ViewDefBounds) => ViewDefResult[] ) { const fieldKey = "data"; const pivotDateGroups = new Map(); @@ -274,7 +274,7 @@ export function computeTimelineLayout( groupNames.push({ type: "text", text: Math.ceil(maxTime).toString(), x: Math.ceil(maxTime - minTime) * scaling, y: 0, height: fontHeight, fontSize, payload: undefined }); } - const divider = { type: "div", color: "black", x: 0, y: 0, width: panelDim[0], height: 1 } as any; + const divider = { type: "div", color: "black", x: 0, y: 0, width: panelDim[0], height: 1, payload: undefined }; return normalizeResults(panelDim, fontHeight, childPairs, docMap, poolData, viewDefsToJSX, groupNames, (maxTime - minTime) * scaling, [divider]); function layoutDocsAtTime(keyDocs: Doc[], key: number) { @@ -298,7 +298,7 @@ export function computeTimelineLayout( } function normalizeResults(panelDim: number[], fontHeight: number, childPairs: { data?: Doc, layout: Doc }[], docMap: Map, - poolData: Map, viewDefsToJSX: (views: any) => ViewDefResult[], groupNames: ViewDefBounds[], minWidth: number, extras: ViewDefBounds[]) { + poolData: Map, viewDefsToJSX: (views: ViewDefBounds) => ViewDefResult[], groupNames: ViewDefBounds[], minWidth: number, extras: ViewDefBounds[]) { const grpEles = groupNames.map(gn => ({ x: gn.x, y: gn.y, width: gn.width, height: gn.height }) as ViewDefBounds); const docEles = childPairs.filter(d => docMap.get(d.layout)).map(pair => docMap.get(pair.layout) as ViewDefBounds); diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index f2c4cda34..ea3805b65 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -441,7 +441,7 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { const miny = this.childDataProvider(docs[0]).y;//docs.length ? NumCast(docs[0].y) : 0; const maxx = this.childDataProvider(docs[0]).width + minx;//docs.length ? NumCast(docs[0].width) + minx : minx; const maxy = this.childDataProvider(docs[0]).height + miny;//docs.length ? NumCast(docs[0].height) + miny : miny; - const ranges = docs.filter(doc => doc).reduce((range, doc) => { + const ranges = docs.filter(doc => doc).filter(doc => this.childDataProvider(doc)).reduce((range, doc) => { const x = this.childDataProvider(doc).x;//NumCast(doc.x); const y = this.childDataProvider(doc).y;//NumCast(doc.y); const xe = this.childDataProvider(doc).width + x;//x + NumCast(layoutDoc.width); @@ -779,7 +779,7 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { const backgroundColor = Cast(viewDef.color, "string"); return [x, y].some(val => val === undefined) ? undefined : { - ele:
this.onViewDefDivClick(e, viewDef)} + ele:
this.onViewDefDivClick(e, viewDef)} style={{ width, height, backgroundColor, transform: `translate(${x}px, ${y}px)` }} />, bounds: viewDef }; diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index b23ab5e49..8b760db00 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -237,7 +237,7 @@ export class CurrentUserUtils { Docs.Create.MulticolumnDocument([], { title: "images", _height: 200, _xMargin: 10, _yMargin: 10 }), Docs.Create.TextDocument("", { title: "contents", _height: 100 }) ], - { _width: 400, _height: 300, title: "slide", _chromeStatus: "disabled", _autoHeight: true }); + { _width: 400, _height: 300, title: "slide", _chromeStatus: "disabled", backgroundColor: "lightGray", _autoHeight: true }); slideTemplate.isTemplateDoc = makeTemplate(slideTemplate); const iconDoc = Docs.Create.TextDocument("", { title: "icon", _width: 150, _height: 30, isTemplateDoc: true, onClick: ScriptField.MakeScript("setNativeView(this)") }); -- cgit v1.2.3-70-g09d2 From 36933b7b647a54aa7bda0600612d34b402d42919 Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Sat, 8 Feb 2020 12:05:08 -0500 Subject: switching scraper --- package-lock.json | 49 ++++--- src/client/documents/Documents.ts | 7 + src/scraping/buxton/json/buxton.json | 145 --------------------- src/scraping/buxton/json/incomplete.json | 95 -------------- src/scraping/buxton/node_scraper.ts | 90 +------------ src/server/ApiManagers/UtilManager.ts | 7 + .../authentication/models/current_user_utils.ts | 1 + 7 files changed, 53 insertions(+), 341 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/package-lock.json b/package-lock.json index a33d060d2..379cd3337 100644 --- a/package-lock.json +++ b/package-lock.json @@ -647,7 +647,7 @@ }, "@types/passport": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@types/passport/-/passport-1.0.0.tgz", + "resolved": "https://registry.npmjs.org/@types/passport/-/passport-1.0.2.tgz", "integrity": "sha512-Pf39AYKf8q+YoONym3150cEwfUD66dtwHJWvbeOzKxnA0GZZ/vAXhNWv9vMhKyRQBQZiQyWQnhYBEBlKW6G8wg==", "requires": { "@types/express": "*" @@ -5391,7 +5391,8 @@ }, "ansi-regex": { "version": "2.1.1", - "bundled": true + "bundled": true, + "optional": true }, "aproba": { "version": "1.2.0", @@ -5409,11 +5410,13 @@ }, "balanced-match": { "version": "1.0.0", - "bundled": true + "bundled": true, + "optional": true }, "brace-expansion": { "version": "1.1.11", "bundled": true, + "optional": true, "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -5426,15 +5429,18 @@ }, "code-point-at": { "version": "1.1.0", - "bundled": true + "bundled": true, + "optional": true }, "concat-map": { "version": "0.0.1", - "bundled": true + "bundled": true, + "optional": true }, "console-control-strings": { "version": "1.1.0", - "bundled": true + "bundled": true, + "optional": true }, "core-util-is": { "version": "1.0.2", @@ -5537,7 +5543,8 @@ }, "inherits": { "version": "2.0.4", - "bundled": true + "bundled": true, + "optional": true }, "ini": { "version": "1.3.5", @@ -5547,6 +5554,7 @@ "is-fullwidth-code-point": { "version": "1.0.0", "bundled": true, + "optional": true, "requires": { "number-is-nan": "^1.0.0" } @@ -5559,17 +5567,20 @@ "minimatch": { "version": "3.0.4", "bundled": true, + "optional": true, "requires": { "brace-expansion": "^1.1.7" } }, "minimist": { "version": "0.0.8", - "bundled": true + "bundled": true, + "optional": true }, "minipass": { "version": "2.9.0", "bundled": true, + "optional": true, "requires": { "safe-buffer": "^5.1.2", "yallist": "^3.0.0" @@ -5586,6 +5597,7 @@ "mkdirp": { "version": "0.5.1", "bundled": true, + "optional": true, "requires": { "minimist": "0.0.8" } @@ -5666,7 +5678,8 @@ }, "number-is-nan": { "version": "1.0.1", - "bundled": true + "bundled": true, + "optional": true }, "object-assign": { "version": "4.1.1", @@ -5676,6 +5689,7 @@ "once": { "version": "1.4.0", "bundled": true, + "optional": true, "requires": { "wrappy": "1" } @@ -5751,7 +5765,8 @@ }, "safe-buffer": { "version": "5.1.2", - "bundled": true + "bundled": true, + "optional": true }, "safer-buffer": { "version": "2.1.2", @@ -5781,6 +5796,7 @@ "string-width": { "version": "1.0.2", "bundled": true, + "optional": true, "requires": { "code-point-at": "^1.0.0", "is-fullwidth-code-point": "^1.0.0", @@ -5798,6 +5814,7 @@ "strip-ansi": { "version": "3.0.1", "bundled": true, + "optional": true, "requires": { "ansi-regex": "^2.0.0" } @@ -5836,11 +5853,13 @@ }, "wrappy": { "version": "1.0.2", - "bundled": true + "bundled": true, + "optional": true }, "yallist": { "version": "3.1.1", - "bundled": true + "bundled": true, + "optional": true } } }, @@ -13785,7 +13804,7 @@ }, "readable-stream": { "version": "2.3.6", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "resolved": "http://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", "requires": { "core-util-is": "~1.0.0", @@ -15703,7 +15722,7 @@ }, "strip-ansi": { "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", "requires": { "ansi-regex": "^2.0.0" @@ -17930,7 +17949,7 @@ }, "wrap-ansi": { "version": "2.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", + "resolved": "http://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=", "requires": { "string-width": "^1.0.1", diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 64dc0d8b7..d647b34e6 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -53,6 +53,7 @@ import { InkingStroke } from "../views/InkingStroke"; import { InkField } from "../../new_fields/InkField"; import { InkingControl } from "../views/InkingControl"; import { RichTextField } from "../../new_fields/RichTextField"; +import { Networking } from "../Network"; const requestImageSize = require('../util/request-image-size'); const path = require('path'); @@ -340,6 +341,12 @@ export namespace Docs { */ export namespace Create { + export async function Buxton() { + console.log(await Networking.FetchFromServer("/newBuxton")); + } + + Scripting.addGlobal(Buxton); + const delegateKeys = ["x", "y", "layoutKey", "_width", "_height", "_panX", "_panY", "_viewType", "_nativeWidth", "_nativeHeight", "dropAction", "_annotationOn", "_chromeStatus", "_forceActive", "_autoHeight", "_fitWidth", "_LODdisable", "_itemIndex", "_showSidebar", "showTitle"]; diff --git a/src/scraping/buxton/json/buxton.json b/src/scraping/buxton/json/buxton.json index 166f4bd49..8371f2cf2 100644 --- a/src/scraping/buxton/json/buxton.json +++ b/src/scraping/buxton/json/buxton.json @@ -43,54 +43,6 @@ "shortDescription": "The Mini-Touch Keyboard is a surprisingly rare device: a laptop-style, small-footprint keyboard with a centrally mounted touch-pad. .", "longDescription": "First released in 2003 with a PS/2 connector (ACK-540PW & ACK-540PB). USB version released in 2006 in either black (ACK-540UB) or white (ACK-540UW). Marketed under different brands, including SolidTek: http: //www. tigerdirect. com/applications/searchtools/item-details. asp? EdpNo=1472243https: //acecaddigital. com/index. php/products/keyboards/mini-keyboards/kb-540 Deltaco: https: //www. digitalimpuls. no/logitech/116652/deltaco-minitastatur-med-touchpad-usb" }, - { - "title": "Braun AG T3 Transistor Radio", - "company": "Braun AG", - "year": 1958, - "primaryKey": [ - "Radio" - ], - "secondaryKey": [ - "Handheld", - "Object", - "Reference" - ], - "originalPrice": 28.57, - "degreesOfFreedom": 2, - "dimensions": { - "length": 152, - "width": 41, - "height": 83, - "unit": "mm" - }, - "shortDescription": "The 1958 Braun T3 transistor radio, designed by Dieter Rams Dieter Rams in conjunction with the Ulm Hochschüle fur Gestaltung (School of Design). An excellent example of the international style of design of the mid-20th century, the T3 radio was the inspiration for the design language of the Apple iPod Classic.", - "longDescription": "The 1958 Braun T3 transistor radio is a classic of the international design style prevalent in the mid-20th century. By its sparse clean lines, it shares characteristics of the style seen in another familiar example, the font Helvetic, which was designed the previous year. The T3 was designed by Dieter Rams, recruited by Braun in 1955, in collaboration with the Ulm Hochschüle fur Gestaltun. . Its design language had a strong influence on that of the original Apple iPod Classic. The connection is made more obvious if one views the radio rotated 90° clockwise, as in one of the accompanying photographs. Here one can easily see the the similarity of proportions, uniformity of colour, angle of corners, location of display (audio versus visual), and the use of a flush rotary wheel controller." - }, - { - "title": "Casio CZ-101 Digital Synthesizer", - "company": "Casio", - "year": 1984, - "primaryKey": [ - "Synthesizer" - ], - "secondaryKey": [ - "Chord", - "Keyboard", - "Object", - "Reference", - "Wheel" - ], - "originalPrice": 499, - "degreesOfFreedom": 1, - "dimensions": { - "length": 20, - "width": 65.7, - "height": 58, - "unit": "mm" - }, - "shortDescription": "One of the first programable polyphonic (8 simultaneous voices) digital synthesizers for less than $500. 00. Used a form of digital synthesis known as Phase Distortion to obtain a rich variety of dynamic timbres. Could be used with batteries or plugged in to power. This one was given to me at the product launch.", - "longDescription": "One of the first programable polyphonic (8 simultaneous voices) digital synthesizers for less than $500. 00. Used a form of digital synthesis known as Phase Distortion to obtain a rich variety of dynamic timbres. Could be used with batteries or plugged in to power. This one was given to me at the product launch. The inclusion of this synthesizer in the collection is as a small reminder of the diversity of keyboard types, and especially, as an example to shed light on chord keyboards. In entering text, for example, chord keyboards are those where more than one key must be simultaneously pressed to enter a single character. Technically, this includes any keyboard with a SHIFT key. Interestingly, piano-type like keyboards like that on the Casio-CZ-101 probably don’t conform to this definition of chording, despite its ability to play musical chords. On the other hand, flutes and trumpets definitely do fall within the definition. Why? With piano-like keyboards, each unique note has a single unique key dedicated to it. When one plays a chord, i. e. , simultaneously presses multiple keys, the result is a chord of notes – the note associated with each depressed key sounds. On the other hand, with trumpet valves or flute keys, only one note is produced at a time. It is the combination of keys pressed (coupled with breath) which determines the pitch of that single note. This is far closer to entering text with a chord keyboard, where each chord enters a single unique character." - }, { "title": "Contour Design UniTrap ", "company": "Contour Design", @@ -136,32 +88,6 @@ "shortDescription": "This mouse is one of the first commercially available mice to be sold publicly. It is known as the Swiss mouse, and yes, the roller mechanism was designed by a Swiss watchmaker. Coincidentally, the company that made it, Depraz, is based in Apples, Switzerland. Their success in selling this mouse is what caused Logitech to switch from a software development shop to one of the world’s leading suppliers of mice and other input devices.", "longDescription": "DePraz began manufacturing in 1980, but following design built in 1979. Logitech started selling it in 1982. It was one of the first mass produced mice, one of the first available ball mice, as well as to have an optical shaft encoder – thereby improving linearity. An interesting fact, given its Swiss heritage, is that its designer, André Guignard, was trained as a Swiss watch maker. Unlike most modern mice, the DePraz, or “Swiss” mouse had a quasi-hemispherical shape. Hence, it was held in a so-called “power-grip”, much as one would grip a horizontally held ball – the thumb and small finger applying pressure on each side, with added support from the weight/friction of the palm on the back of the mouse. In this posture, the three middle fingers naturally positioning themselves over the three buttons mounted at the lower edge of the front. Largely freed of grip pressure, by grace of thumb and little finger, the middle fingers had essentially freedom of motion to independently operate the buttons. Each having a dedicated finger, the buttons could be easily pushed independently or in any combination. Like the three valves on a trumpet, this ability to “chord” extended the three physical buttons to have the power of seven. The down-side of this “turtle shell” form factor is that it placed the hand in a posture in which mouse movement relied more of the larger muscle groups of the arm to wrist, rather than wrist to fingers – the latter being the approach taken in most subsequent mice. The original Swiss Mouse was developed at École Polytechnique Fédérale de Lausanne by a project led by Jean-Daniel Nicoud, who was also responsible for the development of its optical shaft encoder. To augment their revenue stream, Logitech, then a software and hardware consulting company for the publishing industry, acquired marketing rights for North America. Mouse revenue quickly overshadowed that from software. In 1983, Logitech acquired DePraz, named the Swiss Mouse the “P4”, and grew to become one of the largest input device manufacturer in the world. One curious coincidence is that they were founded in the town of Apples, Switzerland." }, - { - "title": "FingerWorks TouchStream LP", - "company": "FingerWorks", - "year": 2002, - "primaryKey": [ - "Keyboard" - ], - "secondaryKey": [ - "Foldable", - "Gesture", - "Keyboard", - "Multi-touch", - "Reskin", - "Touchpad" - ], - "originalPrice": 339, - "degreesOfFreedom": 2, - "dimensions": { - "length": 180, - "width": 140, - "height": 9, - "unit": "mm" - }, - "shortDescription": "The TouchStream is a keyboard based on a pair of multi-touch pads. These can sense key taps and finger gestures. The “keys” are graphic. They are flush with the pad and have no mechanical movement. There are however, small raised points to help position the hands on the keyboard eyes-free typing, but these still allow the fingers slide easily on the surface when gesturing, such as when emulating a mouse. . The keyboard is independent of the base. It can be folded in half for compact portability. It can also be placed conveniently over a laptop’s keyboard as a replacement which then also enables the gesture enhancements to be used on the road. Although not obvious to the eye, this is the core technology which, after being acquired by Apple, evolved into the iPhone’s multi-touch capability.", - "longDescription": "Named FingerBoard during development, this product was relabeled TouchStream in October 2001 as the release date approached. when finally shipped, was renamed TouchStreamThe very rare original stand for this device was a gift from Sean Gerety, Atlanta, GA." - }, { "title": "One Laptop Per Child (OLPC) XO-1", "company": "One Laptop Per Child (OLPC)", @@ -186,76 +112,5 @@ }, "shortDescription": "The OLPC XO-1 is very innovative device that nevertheless raises serious issues about technology and social responsibility. It is included in the collection primarily as a warning against technological hubris, and the fact that no technologies are neutral from a social-cultural perspective.", "longDescription": "IntroductionI have this computer in my collection as a reminder of the delicate relationship between object and purpose, and how no matter how well one does on the former, it will likely have no impact on making a wanting concept achieve the stated (and even valid) purpose any better. I include it in the collection as a cautionary tale of how the object may help sell a concept, regardless how ill-conceived – even to those who should know better, had they applied the most basic critical thinking. For consumers, investors and designers, its story serves as a cautionary reminder to the importance of cultivating and retaining a critical mind and questioning perspective, regardless of how intrinsically seductive or well-intentioned a technology may be. From the perspective of hardware and software, what the One Laptop Per Child (OLPC) project was able to accomplish is impressive. In general, the team delivered a computer that could be produced at a remarkably low price – even if about double that which was targeted. Specifically, the display, for example, is innovative, and stands out due to its ability to work both in the bright sun (reflective) as well as in poorly lit spaces (emissive) – something that goes beyond pretty much anything else that is available on today’s (2017) slate computers or e-readers. In short, some excellent work went into this machine, something that is even more impressive, given the nature of the organization from which it emerged. The industrial design was equally impressive. Undertaken by Yves Behar’s FuseprojectUltimately, however, the machine was a means to an end, not the end itself. Rather than a device, the actual mission of the OLPC project was: … to empower the world's poorest children through education. Yet, as described by in their materials, the computer was intended to play a key role in this: With access to this type of tool [the computer], children are engaged in their own education, and learn, share, and create together. They become connected to each other, to the world and to a brighter future. Hence, making a suitable computer suitable to that purpose and the conditions where it would be used, at a price point that would enable broad distribution, was a key part of the project. The Underlying Belief System of the OLPC ProjectSince they are key to the thinking behind the OLPC project, I believe if fair to frame my discussion around the following four questions: Will giving computers to kids in the developing world improve their education? Will having a thus better-educated youth help bring a society out of poverty? Can that educational improvement be accomplished by giving the computers to the kids, with no special training for teachers? Should this be attempted on a global scale without any advance field trials or pilot studies? From the perspective of the OLPC project, the answer to every one of these questions is an unequivocal “yes”. In fact, as we shall see, any suggestion to the contrary is typically answered by condescension and/or mockery. The answers appear to be viewed as self-evident and not worth even questioning. Those who have not subscribed to this doctrine might call such a viewpoint hubris. What staggers me is how the project got so far without the basic assumptions being more broadly questioned, much less such questions being seriously addressed by the proponents. How did seemingly otherwise people commit to the project, through their labour or financial investment, given the apparently naïve and utopian approach that it took? Does the desire to do good cloud judgment that much? Are we that dazzled by a cool technology or big hairy audacious goal? Or by a charismatic personality? To explain my concern, and what this artifact represents to me, let me just touch on the four assumptions on which the project was founded. Will giving computers to kids in the developing world improve education? The literature on this question is, at best, mixed. What is clear is that one cannot make any assumption that such improvements will occur, regardless of whether one is talking about the developing world or suburban USA. For example, in January 2011, The World Bank published the following study: Can Computers Help Students Learn? From Evidence to Policy, January 2011, Number 4, The World Bank. A public-private partnership in Colombia, called Computers for Education, was created in 2002 to increase the availability of computers in public schools for use in education. Since starting, the program has installed more than 73, 000 computers in over 6, 300 public schools in more than 1, 000 municipalities. By 2008, over 2 million students and 83, 000 teachers had taken part. This document reports on a two-year study to determine the impact of the program on student performance. Students in schools that received the computers and teacher training did not do measurably better on tests than students in the control group. Nor was there a positive effect on other measures of learning. Researchers did not find any difference in test scores when they looked at specific components of math and language studies, such as algebra and geometry, and grammar and paraphrase ability in Spanish. But report also notes that results of such studies are mixed: Studies on the relationship between using computers in the classroom and improved test scores in developing countries give mixed results: A review of Israel’s Tomorrow-98 program in the mid-1990s, which put computers in schools across the country, did not find any impact on math and Hebrew language scores. But in India, a study of a computer-assisted learning program showed a significant positive impact on math scores. One thing researchers agree on, more work is needed in this field. Before moving on, a search of the literature will show that these results are consistent with those that were available in the literature at the time that the project was started. The point that I am making is not that the OLPC project could not be made to work; rather, that it was wrong to assume that it would do so without spending at least as much time designing the process to bring that about, as was expended designing the computer itself. Risk is fine, and something that can be mitigated. But diving in under the assumption that it would just work is not calculated risk, it is gambling - with other people’s lives, education and money. Will a better educated population help bring a society out of poverty? I am largely going to punt on this question. The fact is, I would be hard pressed to argue against education. But let us grant that improving education in the developing world is a good thing. The appropriate question is: is the approach of the OLPC project a reasonable or responsible way to disburse the limited resources that are available to address the educational challenges of the developing world? At the very least, I would suggest that this is a topic worthy of debate. An a priori assumption that giving computers is the right solution is akin to the, “If you build it they will come” approach seen in the movie, Field of Dreams. The problem here is that this is not a movie. There are real lives and futures that are at stake here – lives of those who cannot afford to see the movie, much less have precious resources spent on projects that are not well thought through. Can that improvement be accomplished by just giving the computers to the kids without training teachers? Remarkably, the OLPC Project’s answer is an explicit, “Yes”. In a TED talk filmed in December 2007, the founder of the OLPC initiative, Nicholas Negroponte states: “When people tell me, you know, who’s going to teach the teachers to teach the kids, I say to myself, “What planet do you come from? ” Okay, there’s not a person in this room [the TED Conference], I don’t care how techy you are, there’s not a person in this room that doesn’t give their laptop or cell phone to a kid to help them debug it. Okay, we all need help, even those of us who are very seasoned. ”Let us leave aside the naïvete of this statement stemming from the lack of distinction between ability to use applications and devices versus the ability to create and shape them. A failure of logic remains in that those unseasoned kids are part of “us”, as in “we all need help”. Where do the kids go for help? To other kids? What if they don’t know? Often they won’t. After all, the question may well have to do with a concept in calculus, rather than how to use the computer. What then? No answer is offered. Rather, those who dare raise the serious and legitimate concerns regarding teacher preparation are mockingly dismissed as coming from another planet! Well, perhaps they are. But in that case, there should at least be some debate as to who lives on which planet. Is it the people raising the question or the one dismissing the concern that lives in the real world of responsible thought and action? Can this all be accomplished without any advance field trials? Should one just immediately commit to international deployment of the program? As recently as September 2009, Negroponte took part in a panel discussion where he spoke on this matter. He states: I'd like you to imagine that I told you \"I have a technology that is going to change the quality of life. \" And then I tell you \"Really the right thing to do is to set up a pilot project to test my technology. And then the second thing to do is, once the pilot has been running for some period of time, is to go and measure very carefully the benefits of that technology. \"And then I am to tell you that what we are going to is very scientifically evaluate this technology, with control groups - giving it to some, giving it to others. And this all is very reasonable until I tell you the technology is electricity. And you say \"Wait, you don't have to do that!\"But you don't have to do that with laptops and learning either. And the fact that somebody in the room would say the impact is unclear is to me amazing - unbelievably amazing. There's not a person in this room who hasn't bought a laptop for their child, if they could afford it. And you don't know somebody who hasn't done it, if they can afford it. So there's only one question on the table and that's, “How to afford it? ” That's the only question. There is no other question - it's just the economics. And so, when One Laptop Per Child started, I didn't have the picture quite as clear as that, but we did focus on trying to get the price down. We did focus on those things. Unfortunately, Negroponte demonstrates his lack of understanding of both the history of electricity and education in this example. His historical mistake is this: yes, it was pretty obvious that electricity could bring many benefits to society. But what happened when Edison did exactly what Negroponte advocates? He almost lost his company due to his complete (but mistaken) conviction that DC, rather the AC was the correct technology to pursue. As with electricity, yes, it is rather obvious that education could bring significant benefits to the developing world. But in order to avoid making the same kind of expensive mistake that Edison did, perhaps one might want to do one’s best to make sure that the chosen technology is the AC, rather than DC, of education. A little more research, and a little less hubris might have put the investments in Edison and the OLPC to much better use. But the larger question is this: in what way is it responsible for the wealthy western world to advocate an untested and expensive (in every sense) technological solution on the poorest nations in the world? If history has taught us anything, it has taught us that just because our intentions are good, the same is not necessarily true for consequences of our actions. Later in his presentation, Negroponte states: … our problems are swimming against very naïve views of education. With this, I have to agree. It is just whose views on education are naïve, and how can such views emerge from MIT, no less, much less pass with so little critical scrutiny by the public, the press, participants, and funders? In an interview with Paul Marks, published in the New Scientist in December 2008, we see the how the techno-centric aspect of the project plays into the ostensible human centric purpose of the project. Negroponte’s retort regarding some of the initial skepticism that the project provoked was this: “When we first said we could build a laptop for $100 it was viewed as unrealistic and so 'anti-market' and so 'anti' the current laptops which at the time were around $1000 each, \" Negroponte said. \"It was viewed as pure bravado - but look what happened: the netbook market has developed in our wake. \" The project's demands for cheaper components such as keyboards, and processors nudged the industry into finding ways to cut costs, he says. \"What started off as a revolution became a culture. \"Surprise, yes, computers get smaller, faster, and cheaper over the course of time, and yes, one can even grant that the OLPC project may have accelerated that inevitable move. And, I have already stated my admiration and respect for the quality of the technology that was developed. But in the context of the overall objectives of the project, the best that one can say is, “Congratulations on meeting a milestone. ” However, by the same token, one might also legitimately question if starting with the hardware was not an instance of putting the cart before the horse. Yes, it is obviously necessary to have portable computers in the first place, before one can introduce them into the classroom, home, and donate them to children in the developing world. But it is also the case that small portable computers were already in existence and at the time that the project was initiated. While a factor of ten more expensive than the eventual target price, they were both available and adequate to support limited preliminary testing of the underlying premises of the project in an affordable manner. That is, before launching into a major - albeit well-intentioned – hardware development project, it may have been prudent to have tested the underlying premises of its motivation. Here we have to return to the raison d’être of the initiative: … to empower the world's poorest children through educationHence, the extent to which this is achieved from a given investment must be the primary metric of success, as well as the driving force of the project. Yet, that is clearly not what happened. Driven by a blind Edisonian belief in their un-tested premise, the project’s investments were overwhelmingly on the side of technology rather than pedagogy. Perhaps the nature and extent of the naïve (but well-meaning) utopian dream underlying the project is captured in the last part of the interview, above: Negroponte believes that empowering children and their parents with the educational resources offered by computers and the Internet will lead to informed decisions that improve democracy. Indeed, it has led to some gentle ribbing between himself and his brother: John Negroponte - currently deputy secretary of state in the outgoing Bush administration and the first ever director of national intelligence at the National Security Agency. \"I often joke with John that he can bring democracy his way - and I'll bring it mine, \" he says. Apparently providing inexpensive laptops to children in the developing world is not only going to raise educational standards, eradicate poverty, it is also going to bring democracy! All that, with no mention of the numerous poor non-democratic countries that have literacy levels equal to or higher than the USA (Cuba might be one reasonable example). The words naïve technological-utopianism come to mind. I began by admitting that I was conflicted in terms of this project. From the purely technological perspective, there is much to admire in the project’s accomplishments. Sadly, that was not the project’s primary objective. What appears to be missing throughout is an inability to distinguish between the technology and the purpose to which is was intended to serve. My concern in this regard is reflected in a paper by Warschauer & Ames(2010). The analysis reveals that provision of individual laptops is a utopian vision for the children in the poorest countries, whose educational and social futures could be more effectively improved if the same investments were instead made on more sustainable and proven interventions. Middle- and high-income countries may have a stronger rationale for providing individual laptops to children, but will still want to eschew OLPC’s technocentric vision. In summary, OLPC represents the latest in a long line of technologically utopian development schemes that have unsuccessfully attempted to solve complex social problems with overly simplistic solutions. There is a delicate relationship between technology and society, culture, ethics, and values. What this case study reflects is the fact that technologies are not neutral. They never are. Hence, technological initiatives must be accompanied by appropriate social, cultural and ethical considerations – especially in projects such as this where the technologies are being introduced into particularly vulnerable societies. That did not happen here, The fact that this project got the support that it did, and has gone as far as it has, given the way it was approached, is why this reminder – in the form of this device – is included in the collection. And if anyone ever wonders why I am so vocal about the need for public discourse around technology, one need look no further than the OLPC project." - }, - { - "title": "TASA Model 55 ASCII Keyboard", - "company": "TASA (Touch Activated Switch Arrays)", - "year": 1979, - "primaryKey": [ - "Keyboard" - ], - "secondaryKey": [ - "Pad", - "Touch" - ], - "originalPrice": 80, - "degreesOfFreedom": 0, - "dimensions": { - "length": 382.27, - "width": 158.75, - "height": 8.255, - "unit": "mm" - }, - "shortDescription": "This touch-sensitive keyboard is especially suited for super clean environments, such as hospitals, and those which are just the opposite. The reason is that, being completely flat, there are no crack or gaps where dirt or bacteria can accumulate. This same property enables it to be easily cleaned. However, the reason that I got this keyboard because it was silent – there are no mechanical key-clicks. Hence, for example, it enabled me to soundlessly enter data to my digital musical instrument during a concert or while recording.", - "longDescription": "This is a solid-state touch-sensitive keyboard with no moving parts. Because its surface is flat, the only way one knows that it is a QWERTY keyboard is by the graphical representation on its surface. One types by placing one’s fingers on pictures of keys, rather than physical/mechanical keycaps. Because of the lack of the tactile feedback associated with conventional keyboards, as expected, typing speed and/or accuracy will be compromised with this keyboard. And yet, this keyboard brings real value in certain situations, and in so doing, it provides a good example of the rule: Everything is best for something and worst for something else. Because the is especially suited for super clean environments, such as hospitals, and those which are just the opposite. The reason is that, being completely flat, there are no crack or gaps where dirt or bacteria can accumulate. This same property enables it to be easily cleaned. However, the reason that I got this keyboard because it was silent – there are no mechanical key-clicks. Hence, for example, it enabled me to soundlessly enter data to my digital musical instrument during a concert or while recording. This is one of a number of capacitive touch-sensing input devices produced in the period around 1981 by Touch Activated Switch Arrays (TASA). The others included a touch-sensitive linear controller, the Ferinstat, which could function as a linear slider/fader, for applications such as audio or process control. These came in two lengths and are included in the collection. There were also the Model 16 Micro Proximity Keyboards, which were 16-button keyboards, arranged in a 4x4 array of touch-sensitive buttons that included a touch-sensitive numerical keypad. They also demonstrated a small, capacitive touch-sensitive touch pad, not unlike what one sees on today’s laptops, for example." - }, - { - "title": "HandyKey (TekGear) Twiddler ", - "company": "HandyKey (TekGear)", - "year": 1991, - "primaryKey": [ - "Chord", - "Keyboard" - ], - "secondaryKey": [ - "Gesture", - "Joystick", - "Keyboard", - "Reality", - "Virtual", - "Vr", - "Wearable" - ], - "originalPrice": 199, - "degreesOfFreedom": 2, - "dimensions": { - "length": 128, - "width": 45, - "height": 50, - "unit": "mm" - }, - "shortDescription": "The Twiddler is a one-hand chord keyboard with integrated pointing capability, which can control the cursor in a joystick-like manner. This was a favourite device of the early Cyborg wearable-computer community.", - "longDescription": "……. . Note: Lyons, et al. abstract: An experienced user of the Twiddler, a one--handed chording keyboard, averages speeds of 60 words per minute with letter--by--letter typing of standard test phrases. This fast typing rate coupled with the Twiddler's 3x4 button design, similar to that of a standard mobile telephone, makes it a potential alternative to multi--tap for text entry on mobile phones. Despite this similarity, there is very little data on the Twiddler's performance and learnability. We present a longitudinal study of novice users' learning rates on the Twiddler. Ten participants typed for 20 sessions using two different methods. Each session is composed of 20 minutes of typing with multi--tap and 20 minutes of one--handed chording on the Twiddler. We found that users initially have a faster average typing rate with multi--tap; however, after four sessions the difference becomes negligible, and by the eighth session participants type faster with chording on the Twiddler. Furthermore, after 20 sessions typing rates for the Twiddler are still increasing." - }, - { - "title": "Blue Orb Inc. OrbiTouch", - "company": "Blue Orb Inc", - "year": 2002, - "primaryKey": [ - "Joystick" - ], - "secondaryKey": [ - "Keyboard" - ], - "originalPrice": 695, - "degreesOfFreedom": 4, - "dimensions": { - "length": 482.6, - "width": 228.6, - "height": 74.2, - "unit": "mm" - }, - "shortDescription": "On the one hand, this device has the overall footprint of a keyboard, and it is used to enter text. And yet, it is two wide, flat, spring-loaded, self-returning joysticks, which are used to enter characters, rather than the keys that we typically employ. To add to the unconventional nature of this device, one enters text via these two joysticks by means of something called radial menus, one for each hand. And, in keeping with many keyboards, such as those with an integrated touch pad, the OrbiTouch also enables mouse like capabilities, such as pointing and selecting, also by means of one of the joysticks.", - "longDescription": "Keyboards, Joysticks and Hierarchic Radial MenusIntroductionWhen you first look at this device, you might guess that it is some kind of keyboard. It even says so on the box and on the device itself. The keyboard-like footprint might reinforce this notion, as might the alphanumeric characters in the grey ring around the circular orb on the right-hand. On the other hand, if this is a keyboard, where are the keys? Reading the labels more carefully sheds light on the paradox: there are none. This is a “keyless keyboard. ” Yes, this is a contradiction in terms. But it is just such curiosities that make devices like this potentially interesting. Hence, we shall take a reasonably deep dive to see what might be revealed. Let’s start by trying to understand what the rationale was for landing on this particular design. The orbiTouch was developed by an industrial engineering doctoral student at the University of Central Florida, Peter McAlindon. His goal was to develop a means of text entry that minimized hand and wrist motion. The intent was to reduce the incidence of repetitive stress injury. A fair bit of research was undertaken between initial concept and commercial release. This can be accessed online, and doing so is a worthwhile exercise. Let us now turn our eye to the physical device in order to get a sense of where all of this landed. The Physical DeviceThe orbiTouch is dominated by two large circular “orbs. ” To my eye, their form initially practically screamed out, “I am a rotary control - Turn me!” However, appearances can be deceptive. Rather than dials, the orbs turn out to be a pair of a joysticks of a particular type. Rather than the stick-tilting motion typical of most, these “joysticks” are operated by moving them along the horizontal plane. In this they are a close cousins of the Altra Felix and KA Design Turbo Puck, both also in the collection. However, in contrast with the Felix and Turbo Puck, whose handles are “floating” (if you let go, they remain in the position where you released your grip), the orbs are “self-centering. ” That is, when released, internal springs return the orbs to their neutral central “home” position. In this, they behave much like the Gravis joystick in the collection, for example. At a finer level of detail, the orbs are specific class of joystick: “8-way joy-switches”. The term”8-way” indicates that only movement along the 8 main axes of the compass are sensed. As to the word “switch”, think of each orb as 8 switches, any one of which can be turned on by moving the orb in one of the 8 directions. (Conversely, they are turned off when the orb is released and returns to home position). Unlike an analogue joystick, such switches do not, and cannot, report how far or fast the orb has moved in any particular direction, nor how much pressure might be applied in the process. While limited, joy-switches provide a less complex and lower cost solution that are appropriate in situations where this additional data is not needed. There are several examples of joy-switches in the collection, especially video game controllers. One of the most iconic examples is the Atari CX-40 controller, which is a 4-way joy-switch. To recap, the orbiTouch is a bi-manual device for entering text by means of two orb-shaped planer-moving 8-way self-centering joy-switches. Having swallowed that mouth-full, let us now explore how text is entered using such a transducer. Entering TextIn general, a character or function is input by moving the two orbs. Which character or function depends on the direction (if any) each of the orbs has moved. For example, if both the left and right orb move west (left), the character “a” is entered. On the other hand, if the right orb again moves west, but the left one east (right), then the character input is “e”. How or why this is the case can be explained with the help of some images. For easier reading, the figure below shows the labels around the orbs in an exploded view. Notice that for both orbs, there is a label segment for each of its 8 directions. Since the example discussed entering an “a” and an “e”, each of which involved the right orb moving west (left) let’s look at the associated label segment in even more detail. Like all of the label segments for the right orb, this one consists of six areas containing text, each with a distinct background colour: red, yellow, green, orange and blue for the letters A through E, respectively, and black for the region containing “BACKSPACE”. Now look again at previous image and notice that each of these colours matches the label associated with one of the directions of the left orb. Text is entered using a two part process. Moving the right orb to the left/west specifies that you are going to enter one of: a, b, c, d, e, or BACKSPACE. (Like most keyboards, despite the labels on the key-caps being upper case, lower-case characters are entered unless the shift key is depressed. )Moving the left orb in the direction whose label corresponds to the background colour of the desired character causes that character to be entered. Hence, with the right orb held in the left/west position, one can enter the sequence, “abcde”, followed by a Backspace, by sequentially moving the left orb west (red), north-west (yellow), north (green), north-east (orange), east (blue) and south (black). The same technique can then be used to access all the characters and commands found in the right orb’s labels. Special ModesThere is one thing to add at this point: While entering printing characters always requires the use of both orbs, some actions can be performed using the left orb only. This can be inferred by the text that accompanies some of the left orb’s labels. For example, moving the left orb north (green) in quick succession (analogous to a double-click on a mouse), indicates that SHIFT will apply to the next character entered. Likewise, doing the same thing in the south-west (grey) direction applies the Caps Lock mode, i. e. , SHIFT will be applied to all subsequent entries until the mode is cancelled. These one-handed special modes/functions are summarized in the image below. Of these, the only one that I want to discuss at the moment is the ability of the orbiTouch to switch from entering text to controlling the screen cursor. This is done by moving the left orb south (black) twice in quick succession. When this is done, the right orb controls the cursor movement – the cursor moves continuously in the direction that you move the orb. In this, any doubts that you had about me characterizing the orbs as joysticks should disappear, since this cursor control is classic joystick behaviour. One issue of note is that the label describes this as “mouse” not “joystick”, which while understandable, is incorrect. Finally, before moving on to the next topic, note that while the right orb controls the movement of the screen cursor in mouse mode, movement of the left or left/west or right/east is taken as a left and right mouse button press, respectively. Remembering that the premise here is that the hands don’t have to move from the orbiTouch in order switch between typing and pointing tasks. But that doesn’t mean that the overhead in switching between the tasks is removed. One type of overhead is just substituted for another. And, the moded nature of the orbiTouch means that the option of parallel pointing-typing actions are eliminated. Rather than criticism, I mention these points to indicate the need to be mindful of the trade-offs and consequences of different design decisions - consequences that the designer should be aware of. Going Meta: What’s Really Going On? I want to approach doing so by stepping back, and approaching the underlying method of “typing” by going “meta”. That is, I want to jump up a lever of abstraction, beyond the physical device (for the moment), and explain what is going on at the conceptual level. The rest of the text is in much rougher form …. What will be revealed, if we do so, is that text is entered by means of the parallel use of two 8-direction radial menus. So what is a radial menu? These are the neglected cousins of the linear menus that populate conventional graphical user interfaces. The difference is that one makes a selection by the direction of movement, rather than the distance (as in the case with linear menus). It turns out that people can learn these quickly if the directions correspond to the 8 main points of the compass. For example, in a program menu, moving up (North) might mean Print, down (South) could mean Save, and moving down to the right (South East), Save As. Like linear menus, these menus can also be hierarchic. So, for example, after moving South East in order to specify Save As, a stroke to the left (West) might mean that it should be saved as a PDF file, whereas it would be saved as a Plain Text file if the secondary connected stroke was to the right (East). The reason for this brief tutorial on radial menus is that they pretty much define at the conceptual level how text is entered using the orbiTouch. The eight directions that you can move the orbs defines the menu item selected. And, by having the actual output depending on the combination of the selection made by each of the two orbs, the device can perhaps be best described as entering text using a two-level hierarchic radial menu, where menu selections are made using two planar moving 8-way joy switches. That is quite a mouth-full, and it has taken all of the text above to bring us to the point where there is a reasonable chance that it makes sense. And we still haven’t gotten into the details! it uses hierarchic (2-level) radial menus, but where the hierarchy is space multiplexed, rather than time multiplexed. That is, rather than doing one menu selection after the other, you do them simultaneously, by using a different hand to articulate the selection from each of the two menus. (While the text on the description is sparse still, look at the training cards, etc. and the photos on the page. )At the level of the mental model, there is no question in my mind (actually, I shouldn’t say that, because I am supposed to be an objective researcher who needs empirical data to inform decisions, but what the hell!) that you could give someone who knew how to use this device two isotonic joysticks, such as used with a video game controller, and they would be able to enter text just as fast as with this device. Furthermore, I am sure that if one had a slate capable of sensing both touch and stylus simultaneously, I am certain that the skill would transfer equally to using a touch radial gesture in the non-dominant hand, and stylus (or touch) radial gesture with the other. At the basic level, it is a 2-level radial menu, but where each level is operated independently and quasi-simultaneously by a different one of the operator’s two hands. Level 1: Right HandThis lets the operator select one of eight regionsThe label for each region consists of 6 characters (5 printing and one “special)In selecting one of the regions, one is not selecting any one of the characters of that region; rather, they are just indicating that the character that they want is one of the six in that regionEach of the characters in a region has a different background colour: blue, orange, green, yellow, red and black. Level 2: Left HandThis lets the operator select one of eight regionsEach region is labeled by a single colourAmong the colours that label the eight regions are the same ones used as character background colours in the regions of the right-hand control: blue, orange, green, yellow, red and blackBy the left hand selecting one of these six colours, one indicates which character is to be entered from among the six characters in the region indicated by the right hand – the selected character being the one whose background colour corresponds to the colour selected by the left hand. Hence, there are two 8-way, single level radial menus used. I believe it fair to say that it is, nevertheless, a 2 level radial menu, since both need to be used in order to enter one token. In actual fact, things are more complex, since none of the above covers issues such as all of the special character, punctuation, etc. , that do not appear on the labels of the right hand. To keep things brief, this is why only 6 of the left-hand menu options are used in what is discussed above. The other two options are needed to fill in the gaps. And, even then, the device resorts to something like double-clicks to get special modes and capabilities. For example, double clicking the black (south) region of the left hand turns the right-hand dome into a pointing device, i. e. , a mouse substitute for pointing, etc. I went through the – as it turned out – interesting exercise of translating the two parallel depth-1 radial menus of the orbiTouch UI into two different depth-2, breadth-8 hierarchic radial menus. You can see them in the attached images. The one assumes that the LH “dome” as the first-level selection, and then make the second-level selection with the right-hand dome. The other does the opposite, i. e. , the right-hand dome selection is the first level. It is interesting to compare the two with each other, as well as with both the labeling on the orbiTouch and the Quickstart documentation: The RH level-1 version seems easier to get rudimentary understanding compared to the LH due to clustering of letters and numbers on outer menus. Likewise, for the special characters that are the upper case of the numbersThe physical device is fine for letting you hunt-and-peck, so to speak, for characters, but it is useless for numbers, and most special characters. The documentation provided with the Quick Start (attached is not especially useful in terms of providing heuristics for memorization. While the orbiTouch certainly uses radial menus, it decidedly does not employ marking menus. One of the key things missing is the ability to check and correct before committing to an input, and the lack of ability to backtrack to the start, and therefore abort without entering anything. One thing that I have learned from this exercise is the difference that results due to having self-returning joysticks. Gestures don’t have that attribute. It matters esp w. r. t. the last point. What I like about this story, is how looking at something seemingly very different at the right level of abstraction, teaches us/me something new about something I was supposed to be an expert in. That is, that 2-level hierarchic marking menus can be achieved by two simultaneous single-level MMs. This is why I have the collection, and why I love what I do. There is still delight, despite being a 63-year-old geezer grandfather. The orbiTouch Keyless Keyboard was first known as the Keybowl, and the company was formerly known as Keybowl Inc. , and then Blue Orb Inc." } ] \ No newline at end of file diff --git a/src/scraping/buxton/json/incomplete.json b/src/scraping/buxton/json/incomplete.json index 595412e56..4b05a2a86 100644 --- a/src/scraping/buxton/json/incomplete.json +++ b/src/scraping/buxton/json/incomplete.json @@ -56,20 +56,10 @@ "filename": "AlphaSmart_Pro.docx", "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured." }, - { - "filename": "Amazon_Kindle_Keyboard.docx", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, { "filename": "Apple_ADB_Mouse.docx", "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured." }, - { - "filename": "Apple_Adj_Keyboard.docx", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, { "filename": "Apple_Mac_Portable-Katy’s MacBook Air-2.docx", "year": "__ERR__YEAR__TRANSFORM__: NaN cannot be parsed to a numeric value.", @@ -79,10 +69,6 @@ "filename": "Apple_Mac_Portable-Katy’s MacBook Air.docx", "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." }, - { - "filename": "Apple_Mac_Portable.docx", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, { "filename": "Apple_Scroll_Mouse.docx", "year": "__ERR__YEAR__TRANSFORM__: NaN cannot be parsed to a numeric value.", @@ -93,16 +79,6 @@ "filename": "Apple_iPhone.docx", "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." }, - { - "filename": "BAT.docx", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "Bill_Notes_CyKey.docx", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured." - }, { "filename": "Brailler.docx", "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", @@ -115,22 +91,12 @@ "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." }, - { - "filename": "CasioC801.docx", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, { "filename": "CasioTC500.docx", "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." }, - { - "filename": "Casio_Mini.docx", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, { "filename": "Citizen_LC_909.docx", "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", @@ -188,11 +154,6 @@ "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured." }, - { - "filename": "FingerWorks_Prototype.docx", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, { "filename": "Freeboard.docx", "secondaryKey": "ERR__SECONDARYKEY__: outer match was captured.", @@ -200,10 +161,6 @@ "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." }, - { - "filename": "FrogPad.docx", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured." - }, { "filename": "FujitsuPalm.docx", "primaryKey": "ERR__PRIMARYKEY__: outer match was captured.", @@ -238,24 +195,10 @@ "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured." }, - { - "filename": "Gavilan_SC.docx", - "company": "ERR__COMPANY__: outer match wasn't captured.", - "year": "__ERR__YEAR__TRANSFORM__: NaN cannot be parsed to a numeric value.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, { "filename": "Genius_Ring_Mouse.docx", "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." }, - { - "filename": "Grandjean_Stenotype.docx", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, { "filename": "HTC_Touch.docx", "year": "__ERR__YEAR__TRANSFORM__: NaN cannot be parsed to a numeric value.", @@ -329,10 +272,6 @@ "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." }, - { - "filename": "Kindle_3G_lighted_cover.docx", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured." - }, { "filename": "Leatherman_Tread.docx", "primaryKey": "ERR__PRIMARYKEY__: outer match was captured.", @@ -392,10 +331,6 @@ "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." }, - { - "filename": "Microwriter.docx", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, { "filename": "Motorola_DynaTAC.docx", "year": "__ERR__YEAR__TRANSFORM__: NaN cannot be parsed to a numeric value.", @@ -403,21 +338,6 @@ "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." }, - { - "filename": "MousePen.docx", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "NB75D.docx", - "year": "ERR__YEAR__: outer match was captured.", - "primaryKey": "ERR__PRIMARYKEY__: outer match was captured.", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, { "filename": "NewO.docx", "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", @@ -445,21 +365,12 @@ "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured.", "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." }, - { - "filename": "PARCkbd.docx", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured." - }, { "filename": "PadMouse.docx", "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." }, - { - "filename": "Philco_Mystery_Control.docx", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, { "filename": "PowerTrack.docx", "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", @@ -499,12 +410,6 @@ "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." }, - { - "filename": "The_Tap.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, { "filename": "Thumbelina.docx", "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", diff --git a/src/scraping/buxton/node_scraper.ts b/src/scraping/buxton/node_scraper.ts index 117a0af84..ab6c9dcb2 100644 --- a/src/scraping/buxton/node_scraper.ts +++ b/src/scraping/buxton/node_scraper.ts @@ -1,9 +1,7 @@ import { readdirSync, writeFile, existsSync, mkdirSync } from "fs"; import * as path from "path"; import { red, cyan, yellow, green } from "colors"; -import { Database } from "../../server/database"; import { Opt } from "../../new_fields/Doc"; -import { Utils } from "../../Utils"; const StreamZip = require('node-stream-zip'); export interface DeviceDocument { @@ -104,7 +102,6 @@ function correctSentences(raw: string) { return { transformed: raw }; } -const targetMongoCollection = "newDocuments"; const outDir = path.resolve(__dirname, "json"); const successOut = "buxton.json"; const failOut = "incomplete.json"; @@ -119,7 +116,7 @@ function printEntries(zip: any) { } } -export async function wordToPlainText(pathToDocument: string): Promise { +async function wordToPlainText(pathToDocument: string): Promise { const zip = new StreamZip({ file: pathToDocument, storeEntries: true }); const contents = await new Promise((resolve, reject) => { zip.on('ready', () => { @@ -172,7 +169,7 @@ function capitalize(word: string): string { return word.charAt(0).toUpperCase() + word.slice(1); } -export function analyze(path: string, body: string): AnalysisResult { +function analyze(path: string, body: string): AnalysisResult { const device: any = {}; const segments = path.split("/"); @@ -249,90 +246,11 @@ async function writeOutputFile(relativePath: string, data: any[], total: number, }); } -namespace Doc { - - export async function create(fields: T, viewType?: number) { - const dataDocId = Utils.GenerateGuid(); - const dataDoc = { - _id: dataDocId, - fields: { - ...fields, - isPrototype: true, - author: "Bill Buxton" - }, - __type: "Doc" - }; - const viewDocId = Utils.GenerateGuid(); - const viewDoc = { - _id: viewDocId, - fields: { - proto: protofy(dataDocId), - x: 10, - y: 10, - _width: 900, - _height: 600, - _panX: 0, - _panY: 0, - zIndex: 2, - libraryBrush: false, - _viewType: viewType || 4, - _LODdisable: true - }, - __type: "Doc" - }; - await Database.Instance.insert(viewDoc, targetMongoCollection); - await Database.Instance.insert(dataDoc, targetMongoCollection); - return viewDocId; - } - - export function protofy(id: string) { - return { - fieldId: id, - __type: "proxy" - }; - } - - export function proxifyGuids(ids: string[]) { - return ids.map(id => ({ - fieldId: id, - __type: "proxy" - })); - } - - export function listify(fields: any[]) { - return { - fields: fields, - __type: "list" - }; - } - -} - -async function main() { +export async function main() { if (!existsSync(outDir)) { mkdirSync(outDir); } - - const devices = await parseFiles(); - await Database.tryInitializeConnection(); - - const { create, protofy, proxifyGuids, listify } = Doc; - const parentGuid = await Doc.create({ - proto: protofy("collectionProto"), - title: "The Buxton Collection", - data: listify(proxifyGuids(await Promise.all(devices.map(create)))) - }); - const result = await Database.Instance.updateMany( - { "fields.title": "Collection 1" }, - { $push: { "fields.data.fields": { fieldId: parentGuid, __type: "proxy" } } }, - targetMongoCollection - ); - - console.log(result); - console.log(green(`\nSuccessfully inserted ${devices.length} devices into ${targetMongoCollection}.`)); - - Database.disconnect(); - process.exit(0); + return parseFiles(); } main(); \ No newline at end of file diff --git a/src/server/ApiManagers/UtilManager.ts b/src/server/ApiManagers/UtilManager.ts index a4b4b14a9..dbf274e93 100644 --- a/src/server/ApiManagers/UtilManager.ts +++ b/src/server/ApiManagers/UtilManager.ts @@ -4,6 +4,7 @@ import { exec } from 'child_process'; import { command_line } from "../ActionUtilities"; import RouteSubscriber from "../RouteSubscriber"; import { red } from "colors"; +import { main } from "../../scraping/buxton/node_scraper"; export default class UtilManager extends ApiManager { @@ -58,6 +59,12 @@ export default class UtilManager extends ApiManager { }, }); + register({ + method: Method.GET, + subscription: "/newBuxton", + secureHandler: async ({ res }) => res.send(await main()) + }); + register({ method: Method.GET, subscription: "/version", diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 8b760db00..71775bed6 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -58,6 +58,7 @@ export class CurrentUserUtils { { title: "todo item", icon: "check", ignoreClick: true, drag: 'getCopy(this.dragFactory, true)', dragFactory: notes[notes.length - 1] }, { title: "web page", icon: "globe-asia", ignoreClick: true, drag: 'Docs.Create.WebDocument("https://en.wikipedia.org/wiki/Hedgehog", {_width: 300, _height: 300, title: "New Webpage" })' }, { title: "cat image", icon: "cat", ignoreClick: true, drag: 'Docs.Create.ImageDocument("https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg", { _width: 200, title: "an image of a cat" })' }, + { title: "buxton", icon: "faObjectGroup", ignoreClick: true, drag: "Docs.Create.Buxton()" }, { title: "record", icon: "microphone", ignoreClick: true, drag: `Docs.Create.AudioDocument("${nullAudio}", { _width: 200, title: "ready to record audio" })` }, { title: "clickable button", icon: "bolt", ignoreClick: true, drag: 'Docs.Create.ButtonDocument({ _width: 150, _height: 50, title: "Button" })' }, { title: "presentation", icon: "tv", click: 'openOnRight(Doc.UserDoc().curPresentation = getCopy(this.dragFactory, true))', drag: `Doc.UserDoc().curPresentation = getCopy(this.dragFactory,true)`, dragFactory: emptyPresentation }, -- cgit v1.2.3-70-g09d2 From 79e1323acd0d0f95d08a09cefce908e35d0e7558 Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Sat, 8 Feb 2020 17:32:33 -0500 Subject: initial commit, pending png read error bug fix --- .gitignore | 2 +- src/client/documents/Documents.ts | 45 +- .../collectionFreeForm/CollectionFreeFormView.tsx | 2 +- src/scraping/buxton/final/BuxtonImporter.ts | 316 ++++++++++++++ src/scraping/buxton/json/buxton.json | 116 ----- src/scraping/buxton/json/incomplete.json | 468 --------------------- src/scraping/buxton/node_scraper.ts | 256 ----------- src/server/ApiManagers/UtilManager.ts | 38 +- .../authentication/models/current_user_utils.ts | 2 +- 9 files changed, 374 insertions(+), 871 deletions(-) create mode 100644 src/scraping/buxton/final/BuxtonImporter.ts delete mode 100644 src/scraping/buxton/json/buxton.json delete mode 100644 src/scraping/buxton/json/incomplete.json delete mode 100644 src/scraping/buxton/node_scraper.ts (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/.gitignore b/.gitignore index b88fed833..fbf8668ca 100644 --- a/.gitignore +++ b/.gitignore @@ -6,7 +6,7 @@ ClientUtils.ts solr-8.3.1/server/logs/ solr-8.3.1/server/solr/dash/data/tlog/* solr-8.3.1/server/solr/dash/data/index/* -src/scraping/buxton/source/ +src/scraping/buxton/final/source/ src/server/public/files/ src/scraping/acm/package-lock.json src/server/session_manager/logs/**/*.log diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index d647b34e6..f05bb3736 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -54,6 +54,7 @@ import { InkField } from "../../new_fields/InkField"; import { InkingControl } from "../views/InkingControl"; import { RichTextField } from "../../new_fields/RichTextField"; import { Networking } from "../Network"; +import { extname } from "path"; const requestImageSize = require('../util/request-image-size'); const path = require('path'); @@ -341,8 +342,34 @@ export namespace Docs { */ export namespace Create { - export async function Buxton() { - console.log(await Networking.FetchFromServer("/newBuxton")); + export function Buxton() { + const loading = new Doc; + loading.title = "Please wait for the import script..."; + const parent = TreeDocument([loading], { + title: "The Buxton Collection", + _width: 400, + _height: 400 + }); + Networking.FetchFromServer("/buxton").then(response => { + parent.data = new List(); + const devices = JSON.parse(response); + if (!Array.isArray(devices)) { + alert("Improper Buxton import formatting!"); + return; + } + devices.forEach(device => { + const { __images } = device; + delete device.__images; + const { ImageDocument, StackingDocument } = Docs.Create; + if (Array.isArray(__images)) { + const deviceImages = __images.map((url, i) => ImageDocument(url, { title: `image${i}.${extname(url)}` })); + const doc = StackingDocument(deviceImages, { title: device.title }); + Docs.Get.DocumentHierarchyFromJson(device, undefined, doc); + Doc.AddDocToList(parent, "data", doc); + } + }); + }); + return parent; } Scripting.addGlobal(Buxton); @@ -628,7 +655,7 @@ export namespace Docs { * or the result of any JSON.parse() call. * @param title an optional title to give to the highest parent document in the hierarchy */ - export function DocumentHierarchyFromJson(input: any, title?: string): Opt { + export function DocumentHierarchyFromJson(input: any, title?: string, appendToTarget?: Doc): Opt { if (input === undefined || input === null || ![...primitives, "object"].includes(typeof input)) { return undefined; } @@ -638,7 +665,7 @@ export namespace Docs { } let converted: Doc; if (typeof parsed === "object" && !(parsed instanceof Array)) { - converted = convertObject(parsed, title); + converted = convertObject(parsed, title, appendToTarget); } else { (converted = new Doc).json = toField(parsed); } @@ -653,12 +680,12 @@ export namespace Docs { * @returns the object mapped from JSON to field values, where each mapping * might involve arbitrary recursion (since toField might itself call convertObject) */ - const convertObject = (object: any, title?: string): Doc => { - const target = new Doc(); + const convertObject = (object: any, title?: string, target?: Doc): Doc => { + const resolved = target ?? new Doc; let result: Opt; - Object.keys(object).map(key => (result = toField(object[key], key)) && (target[key] = result)); - title && !target.title && (target.title = title); - return target; + Object.keys(object).map(key => (result = toField(object[key], key)) && (resolved[key] = result)); + title && !resolved.title && (resolved.title = title); + return resolved; }; /** diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 2518a4a55..66e4ef1b0 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -807,7 +807,7 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { doFreeformLayout(poolData: Map) { const layoutDocs = this.childLayoutPairs.map(pair => pair.layout); const initResult = this.Document.arrangeInit && this.Document.arrangeInit.script.run({ docs: layoutDocs, collection: this.Document }, console.log); - let state = initResult && initResult.success ? initResult.result.scriptState : undefined; + const state = initResult && initResult.success ? initResult.result.scriptState : undefined; const elements = initResult && initResult.success ? this.viewDefsToJSX(initResult.result.views) : []; this.childLayoutPairs.filter(pair => this.isCurrent(pair.layout)).map((pair, i) => { diff --git a/src/scraping/buxton/final/BuxtonImporter.ts b/src/scraping/buxton/final/BuxtonImporter.ts new file mode 100644 index 000000000..804d65d74 --- /dev/null +++ b/src/scraping/buxton/final/BuxtonImporter.ts @@ -0,0 +1,316 @@ +import { readdirSync, writeFile, mkdirSync, createWriteStream, createReadStream, unlinkSync } from "fs"; +import * as path from "path"; +import { red, cyan, yellow, green } from "colors"; +import { Utils } from "../../../Utils"; +import rimraf = require("rimraf"); +const StreamZip = require('node-stream-zip'); +import * as sharp from 'sharp'; +import { SizeSuffix, DashUploadUtils, InjectSize } from "../../../server/DashUploadUtils"; +import { AcceptibleMedia } from "../../../server/SharedMediaTypes"; + +export interface DeviceDocument { + title: string; + shortDescription: string; + longDescription: string; + company: string; + year: number; + originalPrice: number; + degreesOfFreedom: number; + dimensions: string; + primaryKey: string; + secondaryKey: string; +} + +interface DocumentContents { + body: string; + images: string[]; +} + +interface AnalysisResult { + device?: DeviceDocument; + errors?: any; +} + +type Converter = (raw: string) => { transformed?: T, error?: string }; + +interface Processor { + exp: RegExp; + matchIndex?: number; + transformer?: Converter; +} + +namespace Utilities { + + export function numberValue(raw: string) { + const transformed = Number(raw); + if (isNaN(transformed)) { + return { error: `${transformed} cannot be parsed to a numeric value.` }; + } + return { transformed }; + } + + export function collectUniqueTokens(raw: string) { + return { transformed: Array.from(new Set(raw.replace(/,|\s+and\s+/g, " ").split(/\s+/).map(token => token.toLowerCase().trim()))).map(capitalize).sort() }; + } + + export function correctSentences(raw: string) { + raw = raw.replace(/\./g, ". ").replace(/\:/g, ": ").replace(/\,/g, ", ").replace(/\?/g, "? ").trimRight(); + raw = raw.replace(/\s{2,}/g, " "); + return { transformed: raw }; + } + + export function tryGetValidCapture(matches: RegExpExecArray | null, matchIndex: number): string | undefined { + let captured: string; + if (!matches || !(captured = matches[matchIndex])) { + return undefined; + } + const lower = captured.toLowerCase(); + if (/to come/.test(lower)) { + return undefined; + } + if (lower.includes("xxx")) { + return undefined; + } + if (!captured.toLowerCase().replace(/[….\s]+/g, "").length) { + return undefined; + } + return captured; + } + + export function capitalize(word: string): string { + const clean = word.trim(); + if (!clean.length) { + return word; + } + return word.charAt(0).toUpperCase() + word.slice(1); + } + +} + +const RegexMap = new Map>([ + ["title", { + exp: /contact\s+(.*)Short Description:/ + }], + ["company", { + exp: /Company:\s+([^\|]*)\s+\|/, + transformer: (raw: string) => ({ transformed: raw.replace(/\./g, "") }) + }], + ["year", { + exp: /Year:\s+([^\|]*)\s+\|/, + transformer: Utilities.numberValue + }], + ["primaryKey", { + exp: /Primary:\s+(.*)(Secondary|Additional):/, + transformer: Utilities.collectUniqueTokens + }], + ["secondaryKey", { + exp: /(Secondary|Additional):\s+([^\{\}]*)Links/, + transformer: Utilities.collectUniqueTokens, + matchIndex: 2 + }], + ["originalPrice", { + exp: /Original Price \(USD\)\:\s+\$([0-9\.]+)/, + transformer: Utilities.numberValue + }], + ["degreesOfFreedom", { + exp: /Degrees of Freedom:\s+([0-9]+)/, + transformer: Utilities.numberValue + }], + ["dimensions", { + exp: /Dimensions\s+\(L x W x H\):\s+([0-9\.]+\s+x\s+[0-9\.]+\s+x\s+[0-9\.]+\s\([A-Za-z]+\))/, + transformer: (raw: string) => { + const [length, width, group] = raw.split(" x "); + const [height, unit] = group.split(" "); + return { + transformed: { + dim_length: Number(length), + dim_width: Number(width), + dim_height: Number(height), + dim_unit: unit.replace(/[\(\)]+/g, "") + } + }; + } + }], + ["shortDescription", { + exp: /Short Description:\s+(.*)Bill Buxton[’']s Notes/, + transformer: Utilities.correctSentences + }], + ["longDescription", { + exp: /Bill Buxton[’']s Notes(.*)Device Details/, + transformer: Utilities.correctSentences + }], +]); + +const outDir = path.resolve(__dirname, "json"); +const imageDir = path.resolve(__dirname, "../../../server/public/files/images/buxton"); +const successOut = "buxton.json"; +const failOut = "incomplete.json"; +const deviceKeys = Array.from(RegexMap.keys()); + +export default async function executeImport() { + [outDir, imageDir].forEach(dir => { + rimraf.sync(dir); + mkdirSync(dir); + }); + return parseFiles(); +} + +async function parseFiles(): Promise { + const sourceDirectory = path.resolve(`${__dirname}/source`); + + const candidates = readdirSync(sourceDirectory).filter(file => file.endsWith(".doc") || file.endsWith(".docx")).map(file => `${sourceDirectory}/${file}`); + const imported = await Promise.all(candidates.map(async path => ({ path, body: await extractFileContents(path) }))); + const data = imported.map(({ path, body }) => analyze(path, body)); + + const masterDevices: DeviceDocument[] = []; + const masterErrors: any[] = []; + + data.forEach(({ device, errors }) => { + if (device) { + masterDevices.push(device); + } else { + masterErrors.push(errors); + } + }); + const total = candidates.length; + if (masterDevices.length + masterErrors.length !== total) { + throw new Error(`Encountered a ${masterDevices.length} to ${masterErrors.length} mismatch in device / error split!`); + } + + console.log(); + await writeOutputFile(successOut, masterDevices, total, true); + await writeOutputFile(failOut, masterErrors, total, false); + console.log(); + + return masterDevices; +} + +async function extractFileContents(pathToDocument: string): Promise<{ body: string, images: string[] }> { + const zip = new StreamZip({ file: pathToDocument, storeEntries: true }); + const contents = await new Promise((resolve, reject) => { + zip.on('ready', () => { + let body = ""; + zip.stream("word/document.xml", (error: any, stream: any) => { + if (error) { + reject(error); + } + stream.on('data', (chunk: any) => body += chunk.toString()); + stream.on('end', () => resolve(body)); + }); + }); + }); + const images = (await writeImages(zip)).map(name => `http://localhost:1050/files/images/buxton/${name}`); + zip.close(); + let body = ""; + const components = contents.toString().split(''); + const content = tags[1].replace(/<.*$/, ""); + body += content; + } + return { body, images }; +} + +async function writeImages(zip: any): Promise { + const entryNames = Object.values(zip.entries()).map(({ name }) => name); + const resolved: { mediaPath: string, ext: string }[] = []; + let initialWritePath: string; + entryNames.forEach(name => { + const matches = /^word\/media\/\w+\.(jpeg|jpg|png|gif)/.exec(name); + matches && resolved.push({ mediaPath: name, ext: matches[1] }); + }); + return Promise.all(resolved.map(async ({ mediaPath, ext }) => { + const outName = `upload_${Utils.GenerateGuid()}.${ext}`; + const initialWrite = await new Promise((resolve, reject) => { + zip.stream(mediaPath, (error: any, stream: any) => { + if (error) { + console.error(error); + return reject(error); + } + initialWritePath = `${imageDir}/${outName}`; + const writeStream = createWriteStream(initialWritePath); + stream.on('end', () => resolve(outName)); + stream.on('error', reject); + stream.pipe(writeStream); + }); + }); + const resizers = [ + { resizer: sharp().rotate(), suffix: SizeSuffix.Original }, + ...Object.values(DashUploadUtils.Sizes).map(size => ({ + resizer: sharp().resize(size.width, undefined, { withoutEnlargement: true }).rotate(), + suffix: size.suffix + })) + ]; + const { pngs, jpgs } = AcceptibleMedia; + if (pngs.includes(ext)) { + resizers.forEach(element => element.resizer = element.resizer.png()); + } else if (jpgs.includes(ext)) { + resizers.forEach(element => element.resizer = element.resizer.jpeg()); + } + for (const { resizer, suffix } of resizers) { + await new Promise(resolve => { + const filename = InjectSize(outName, suffix); + console.log(filename); + createReadStream(initialWritePath).pipe(resizer).pipe(createWriteStream(`${imageDir}/${filename}`)) + .on('close', resolve) + .on('error', error => { + console.log(red(error)); + resolve(); + }); + }); + } + unlinkSync(initialWritePath); + return initialWrite; + })); +} + +function analyze(pathToDocument: string, { body, images }: DocumentContents): AnalysisResult { + const filename = path.basename(pathToDocument).replace("Bill_Notes_", ""); + console.log(`Parsing ${filename}...`); + + const device: any = {}; + const errors: any = { filename }; + + for (const key of deviceKeys) { + const { exp, transformer, matchIndex } = RegexMap.get(key)!; + const matches = exp.exec(body); + + let captured = Utilities.tryGetValidCapture(matches, matchIndex ?? 1); + if (!captured) { + errors[key] = `ERR__${key.toUpperCase()}__: outer match ${matches === null ? "wasn't" : "was"} captured.`; + continue; + } + + captured = captured.replace(/\s{2,}/g, " "); + if (transformer) { + const { error, transformed } = transformer(captured); + if (error) { + errors[key] = `__ERR__${key.toUpperCase()}__TRANSFORM__: ${error}`; + continue; + } + captured = transformed; + } + + device[key] = captured; + } + + const errorKeys = Object.keys(errors); + if (errorKeys.length > 1) { + console.log(red(`\n@ ${cyan(filename.toUpperCase())}...`)); + errorKeys.forEach(key => key !== "filename" && console.log(red(errors[key]))); + return { errors }; + } + + device.__images = images; + + return { device }; +} + +async function writeOutputFile(relativePath: string, data: any[], total: number, success: boolean) { + console.log(yellow(`Encountered ${data.length} ${success ? "valid" : "invalid"} documents out of ${total} candidates. Writing ${relativePath}...`)); + return new Promise((resolve, reject) => { + const destination = path.resolve(outDir, relativePath); + const contents = JSON.stringify(data, undefined, 4); + writeFile(destination, contents, err => err ? reject(err) : resolve()); + }); +} \ No newline at end of file diff --git a/src/scraping/buxton/json/buxton.json b/src/scraping/buxton/json/buxton.json deleted file mode 100644 index 8371f2cf2..000000000 --- a/src/scraping/buxton/json/buxton.json +++ /dev/null @@ -1,116 +0,0 @@ -[ - { - "title": "3Dconnexion CadMan 3D Motion Controller", - "company": "3Dconnexion", - "year": 2003, - "primaryKey": [ - "Joystick" - ], - "secondaryKey": [ - "Isometric", - "Joystick" - ], - "originalPrice": 399, - "degreesOfFreedom": 6, - "dimensions": { - "length": 175, - "width": 122, - "height": 43, - "unit": "mm" - }, - "shortDescription": "The CadMan is a 6 degree of freedom (DOF) joystick controller. It represented a significant step towards making this class of is controller affordable. It was mainly directed at 3D modelling and animation and was a “next generation” of the Magellan controller, which is also in the collection.", - "longDescription": "The CadMan is a 6 degree of freedom (DOF) joystick controller. It represented a significant step towards making this class of is controller more affordable. It was mainly directed at 3D modelling and animation and was a “next generation” of the Magellan/SpaceMouse controller, which is also in the collection. Like the Magellan, this is an isometric rate-control joystick. That is, it rests in a neutral central position, not sending and signal. When a force is applied to it, it emits a signal indicating the direction and strength of that force. This signal can then be mapped to a parameter of a selected object, such as a sphere, and – for example – cause that sphere to rotate for as long as, and as fast as, and in the direction determined by, the duration, force, and direction of the applied force. When released, it springs back to neutral position. Note that the force does not need to be directed along a single DOF. In fact, a core feature of the device is that one can simultaneously and independently apply force that asserts control over more than one DOF, and furthermore, vary those forces dynamically. As an aid to understanding, let me walk through some of the underlying concepts at play here by using a more familiar device: a computer mouse. If you move a mouse in a forward/backward direction, the mouse pointer on the screen moves between the screen’s top and bottom. If you think of the screen as a piece of graph paper, that corresponds to moving along the “Y” axis. That is one degree of freedom. On the other hand, you could move the mouse left and right, which causes the mouse to move between the left and right side of the screen. That would correspond to moving along the graph paper’s “X” axis – a second degree of freedom. Yet, you can also move the mouse diagonally. This is an example of independently controlling two degrees of freedom. Now imagine that if you lifted your mouse off your desktop, that your computer could dynamically sense its height as you did so. This would constitute a “flying mouse” (the literal translation of the German word for a “Bat”, which Canadian colleague, Colin Ware, applied to just such a mouse which he built in 1988). If you moved your Bat vertically up and down, perpendicular to the desktop, you would be controlling movement along the “Z” axis - a third degree of freedom. Having already seen that we can move a mouse diagonally, we have established that we need not be constrained to only moving along a single axis. That extends to the movement of our Bat and movement along the “Z” axis. We can control our hand movement in dependently in any or all directions in 3D space. But how does one reconcile the fact that we call the CadMan a “3D controller, and yet also describe it as having 6 degrees of freedom? After all, the example this far demonstrates that our Bat, as described thus far, has freedom on movement in 3 Dimensions. While true, we can extend our example to prove that that freedom to move in 3D is also highly constrained. To demonstrate this, move your hand in 3D space on and above your desktop. However, do so keeping your palm flat, parallel to the desktop with your fingers pointing directly forward. In so doing, you are still moving in 3D. Now, while moving, twist your wrist, while moving the hand, such that your palm is alternatively exposed to the left and right side. This constitutes rotation around the “Y” axis. A fourth DOF. Now add a waving motion to your hand, as if it were a paper airplane diving up and down, while also rocking left and right. But keep your fingers pointing forward. You have now added a fifth DOF, rotation around the “X” axis. Finally, add a twist to your wrist so that your fingers are no longer constrained to pointing forward. This is the sixth degree of freedom, rotation around the “Z” axis. Now don’t be fooled, this exercise could continue. We are not restricted to even six DOF. Imagine doing the above, but where the movement and rotations are measured relative to the Bat’s position and orientation, rather than to the holding/controlling hand, per se. One could imagine the Bat having a scroll wheel, like the one on most mice today. Furthermore, while flying your Bat around in 3D, that wheel could easily be rolled in either forward or backward, and thereby control the size of whatever was being controlled. Hence, with one hand we could assert simultaneous and independent control over 7 DOF in 3D space. This exercise has two intended take-aways. The first is a better working understanding between the notion of Degree of Freedom (DOF) and Dimension in space. Hopefully, the confusion frequently encountered when 3D and 6DOF are used in close context, can now be eliminated. Second, is that, with appropriate sensing, the human hand is capable of exercising control over far more degrees of freedom that six. And if we use the two hands together, the potential number of DOF that one can control goes even further. Finally, it is important to add one more take-away – one which both emerges from, and is frequently encountered when discussing, the previous two. That is, do not equate exercising simultaneous control over a high number of DOF with consciously doing the same number of different things all at once. The example that used to be thrown at me when I started talking about coordinated simultaneously bi-manual action went along the lines of, “Psychology tells us that we cannot do multiple things at once, for example, simultaneously tapping your head and rubbing your stomach. ”Well, first, I can tap my head with one hand while rubbing my stomach with the other. But that is not the point. The whole essence of skill – motor-sensory and cognitive – is “chunking” or task integration. When one appears to be doing many different things at once, if they are skilled, they are consciously doing only one thing. Playing a chord on the piano, for example, or skiing down the hill. Likewise, in flying your imaginary BAT in the previous exercise with the scroll wheel, were you doing 7 things at once, or one thing with 7 DOF? And if you had a Bat in each hand, does that mean you are now doing 14 things at once, or are you doing one thing with 14 DOF? Let me provide a different way of answering this question: if you have ever played air guitar, or “conducted” the orchestra that you are listening to on the radio, you are exercising control over more than 14 DOF. And you are doing exactly what I just said, “playing air guitar” or “conducting an orchestra”. One thing – at the conscious level, which is what matters – despite almost any one thing being able to be deconstructed into hundreds of sub-tasks. As I said the essence of skill: aggregation, or chunking. What is most important for both tool designers and users to be mindful of, is the overwhelming influence that our choice and design of tools impacts the degree to which such integration or chunking can take place. The degree to which the tool matches both the skills that we have already acquired through a lifetime of living in the everyday world, and the demands of the intended task, the more seamless that task can be performed, the more “natural” it will feel, and the less learning will be required. In my experience, it brought particular value when used bimanually, in combination with a mouse, where the preferred hand performed conventional pointing, selection and dragging tasks, while the non-preferred hand could manipulate the parameters of the thing being selected. First variation of the since the 2001 formation of 3Dconnextion. The CadMan came in 5 colours: smoke, orange, red, blue and green. See the notes for the LogiCad3D Magellan for more details on this class of device. It is the “parent” of the CadMan, and despite the change in company name, it comes from the same team." - }, - { - "title": "Adesso ACK-540UB USB Mini-Touch Keyboard with Touchpad", - "company": "Adesso", - "year": 2005, - "primaryKey": [ - "Keyboard" - ], - "secondaryKey": [ - "Pad", - "Touch" - ], - "originalPrice": 59.95, - "degreesOfFreedom": 2, - "dimensions": { - "length": 287, - "width": 140, - "height": 35.5, - "unit": "mm" - }, - "shortDescription": "The Mini-Touch Keyboard is a surprisingly rare device: a laptop-style, small-footprint keyboard with a centrally mounted touch-pad. .", - "longDescription": "First released in 2003 with a PS/2 connector (ACK-540PW & ACK-540PB). USB version released in 2006 in either black (ACK-540UB) or white (ACK-540UW). Marketed under different brands, including SolidTek: http: //www. tigerdirect. com/applications/searchtools/item-details. asp? EdpNo=1472243https: //acecaddigital. com/index. php/products/keyboards/mini-keyboards/kb-540 Deltaco: https: //www. digitalimpuls. no/logitech/116652/deltaco-minitastatur-med-touchpad-usb" - }, - { - "title": "Contour Design UniTrap ", - "company": "Contour Design", - "year": 1999, - "primaryKey": [ - "Re-skin" - ], - "secondaryKey": [ - "Mouse" - ], - "originalPrice": 14.99, - "degreesOfFreedom": 2, - "dimensions": { - "length": 130.5, - "width": 75.7, - "height": 43, - "unit": "mm" - }, - "shortDescription": "This is a plastic shell within which the round Apple iMac G3 “Hockey Puck” mouse can be fit. While the G3 Mouse worked well mechanically, when gripped its round shape gave few cues as to its orientation. Hence, if you moved your hand up, the screen pointer may well have moved diagonally. By reskinning it with the inexpensive Contour UniTrap, the problem went away without the need to buy a whole new mouse.", - "longDescription": "Also add back pointers from devices re-skinned" - }, - { - "title": "Depraz Swiss Mouse", - "company": "Depraz", - "year": 1980, - "primaryKey": [ - "Mouse" - ], - "secondaryKey": [ - "Ball", - "Chord", - "Keyboard", - "Mouse" - ], - "originalPrice": 295, - "degreesOfFreedom": 2, - "dimensions": { - "length": 50.8, - "width": 76.2, - "height": 114.3, - "unit": "mm" - }, - "shortDescription": "This mouse is one of the first commercially available mice to be sold publicly. It is known as the Swiss mouse, and yes, the roller mechanism was designed by a Swiss watchmaker. Coincidentally, the company that made it, Depraz, is based in Apples, Switzerland. Their success in selling this mouse is what caused Logitech to switch from a software development shop to one of the world’s leading suppliers of mice and other input devices.", - "longDescription": "DePraz began manufacturing in 1980, but following design built in 1979. Logitech started selling it in 1982. It was one of the first mass produced mice, one of the first available ball mice, as well as to have an optical shaft encoder – thereby improving linearity. An interesting fact, given its Swiss heritage, is that its designer, André Guignard, was trained as a Swiss watch maker. Unlike most modern mice, the DePraz, or “Swiss” mouse had a quasi-hemispherical shape. Hence, it was held in a so-called “power-grip”, much as one would grip a horizontally held ball – the thumb and small finger applying pressure on each side, with added support from the weight/friction of the palm on the back of the mouse. In this posture, the three middle fingers naturally positioning themselves over the three buttons mounted at the lower edge of the front. Largely freed of grip pressure, by grace of thumb and little finger, the middle fingers had essentially freedom of motion to independently operate the buttons. Each having a dedicated finger, the buttons could be easily pushed independently or in any combination. Like the three valves on a trumpet, this ability to “chord” extended the three physical buttons to have the power of seven. The down-side of this “turtle shell” form factor is that it placed the hand in a posture in which mouse movement relied more of the larger muscle groups of the arm to wrist, rather than wrist to fingers – the latter being the approach taken in most subsequent mice. The original Swiss Mouse was developed at École Polytechnique Fédérale de Lausanne by a project led by Jean-Daniel Nicoud, who was also responsible for the development of its optical shaft encoder. To augment their revenue stream, Logitech, then a software and hardware consulting company for the publishing industry, acquired marketing rights for North America. Mouse revenue quickly overshadowed that from software. In 1983, Logitech acquired DePraz, named the Swiss Mouse the “P4”, and grew to become one of the largest input device manufacturer in the world. One curious coincidence is that they were founded in the town of Apples, Switzerland." - }, - { - "title": "One Laptop Per Child (OLPC) XO-1", - "company": "One Laptop Per Child (OLPC)", - "year": 2007, - "primaryKey": [ - "Computer" - ], - "secondaryKey": [ - "Keyboard", - "Laptop", - "Pad", - "Slate", - "Touch" - ], - "originalPrice": 199, - "degreesOfFreedom": 2, - "dimensions": { - "length": 242, - "width": 228, - "height": 30, - "unit": "mm" - }, - "shortDescription": "The OLPC XO-1 is very innovative device that nevertheless raises serious issues about technology and social responsibility. It is included in the collection primarily as a warning against technological hubris, and the fact that no technologies are neutral from a social-cultural perspective.", - "longDescription": "IntroductionI have this computer in my collection as a reminder of the delicate relationship between object and purpose, and how no matter how well one does on the former, it will likely have no impact on making a wanting concept achieve the stated (and even valid) purpose any better. I include it in the collection as a cautionary tale of how the object may help sell a concept, regardless how ill-conceived – even to those who should know better, had they applied the most basic critical thinking. For consumers, investors and designers, its story serves as a cautionary reminder to the importance of cultivating and retaining a critical mind and questioning perspective, regardless of how intrinsically seductive or well-intentioned a technology may be. From the perspective of hardware and software, what the One Laptop Per Child (OLPC) project was able to accomplish is impressive. In general, the team delivered a computer that could be produced at a remarkably low price – even if about double that which was targeted. Specifically, the display, for example, is innovative, and stands out due to its ability to work both in the bright sun (reflective) as well as in poorly lit spaces (emissive) – something that goes beyond pretty much anything else that is available on today’s (2017) slate computers or e-readers. In short, some excellent work went into this machine, something that is even more impressive, given the nature of the organization from which it emerged. The industrial design was equally impressive. Undertaken by Yves Behar’s FuseprojectUltimately, however, the machine was a means to an end, not the end itself. Rather than a device, the actual mission of the OLPC project was: … to empower the world's poorest children through education. Yet, as described by in their materials, the computer was intended to play a key role in this: With access to this type of tool [the computer], children are engaged in their own education, and learn, share, and create together. They become connected to each other, to the world and to a brighter future. Hence, making a suitable computer suitable to that purpose and the conditions where it would be used, at a price point that would enable broad distribution, was a key part of the project. The Underlying Belief System of the OLPC ProjectSince they are key to the thinking behind the OLPC project, I believe if fair to frame my discussion around the following four questions: Will giving computers to kids in the developing world improve their education? Will having a thus better-educated youth help bring a society out of poverty? Can that educational improvement be accomplished by giving the computers to the kids, with no special training for teachers? Should this be attempted on a global scale without any advance field trials or pilot studies? From the perspective of the OLPC project, the answer to every one of these questions is an unequivocal “yes”. In fact, as we shall see, any suggestion to the contrary is typically answered by condescension and/or mockery. The answers appear to be viewed as self-evident and not worth even questioning. Those who have not subscribed to this doctrine might call such a viewpoint hubris. What staggers me is how the project got so far without the basic assumptions being more broadly questioned, much less such questions being seriously addressed by the proponents. How did seemingly otherwise people commit to the project, through their labour or financial investment, given the apparently naïve and utopian approach that it took? Does the desire to do good cloud judgment that much? Are we that dazzled by a cool technology or big hairy audacious goal? Or by a charismatic personality? To explain my concern, and what this artifact represents to me, let me just touch on the four assumptions on which the project was founded. Will giving computers to kids in the developing world improve education? The literature on this question is, at best, mixed. What is clear is that one cannot make any assumption that such improvements will occur, regardless of whether one is talking about the developing world or suburban USA. For example, in January 2011, The World Bank published the following study: Can Computers Help Students Learn? From Evidence to Policy, January 2011, Number 4, The World Bank. A public-private partnership in Colombia, called Computers for Education, was created in 2002 to increase the availability of computers in public schools for use in education. Since starting, the program has installed more than 73, 000 computers in over 6, 300 public schools in more than 1, 000 municipalities. By 2008, over 2 million students and 83, 000 teachers had taken part. This document reports on a two-year study to determine the impact of the program on student performance. Students in schools that received the computers and teacher training did not do measurably better on tests than students in the control group. Nor was there a positive effect on other measures of learning. Researchers did not find any difference in test scores when they looked at specific components of math and language studies, such as algebra and geometry, and grammar and paraphrase ability in Spanish. But report also notes that results of such studies are mixed: Studies on the relationship between using computers in the classroom and improved test scores in developing countries give mixed results: A review of Israel’s Tomorrow-98 program in the mid-1990s, which put computers in schools across the country, did not find any impact on math and Hebrew language scores. But in India, a study of a computer-assisted learning program showed a significant positive impact on math scores. One thing researchers agree on, more work is needed in this field. Before moving on, a search of the literature will show that these results are consistent with those that were available in the literature at the time that the project was started. The point that I am making is not that the OLPC project could not be made to work; rather, that it was wrong to assume that it would do so without spending at least as much time designing the process to bring that about, as was expended designing the computer itself. Risk is fine, and something that can be mitigated. But diving in under the assumption that it would just work is not calculated risk, it is gambling - with other people’s lives, education and money. Will a better educated population help bring a society out of poverty? I am largely going to punt on this question. The fact is, I would be hard pressed to argue against education. But let us grant that improving education in the developing world is a good thing. The appropriate question is: is the approach of the OLPC project a reasonable or responsible way to disburse the limited resources that are available to address the educational challenges of the developing world? At the very least, I would suggest that this is a topic worthy of debate. An a priori assumption that giving computers is the right solution is akin to the, “If you build it they will come” approach seen in the movie, Field of Dreams. The problem here is that this is not a movie. There are real lives and futures that are at stake here – lives of those who cannot afford to see the movie, much less have precious resources spent on projects that are not well thought through. Can that improvement be accomplished by just giving the computers to the kids without training teachers? Remarkably, the OLPC Project’s answer is an explicit, “Yes”. In a TED talk filmed in December 2007, the founder of the OLPC initiative, Nicholas Negroponte states: “When people tell me, you know, who’s going to teach the teachers to teach the kids, I say to myself, “What planet do you come from? ” Okay, there’s not a person in this room [the TED Conference], I don’t care how techy you are, there’s not a person in this room that doesn’t give their laptop or cell phone to a kid to help them debug it. Okay, we all need help, even those of us who are very seasoned. ”Let us leave aside the naïvete of this statement stemming from the lack of distinction between ability to use applications and devices versus the ability to create and shape them. A failure of logic remains in that those unseasoned kids are part of “us”, as in “we all need help”. Where do the kids go for help? To other kids? What if they don’t know? Often they won’t. After all, the question may well have to do with a concept in calculus, rather than how to use the computer. What then? No answer is offered. Rather, those who dare raise the serious and legitimate concerns regarding teacher preparation are mockingly dismissed as coming from another planet! Well, perhaps they are. But in that case, there should at least be some debate as to who lives on which planet. Is it the people raising the question or the one dismissing the concern that lives in the real world of responsible thought and action? Can this all be accomplished without any advance field trials? Should one just immediately commit to international deployment of the program? As recently as September 2009, Negroponte took part in a panel discussion where he spoke on this matter. He states: I'd like you to imagine that I told you \"I have a technology that is going to change the quality of life. \" And then I tell you \"Really the right thing to do is to set up a pilot project to test my technology. And then the second thing to do is, once the pilot has been running for some period of time, is to go and measure very carefully the benefits of that technology. \"And then I am to tell you that what we are going to is very scientifically evaluate this technology, with control groups - giving it to some, giving it to others. And this all is very reasonable until I tell you the technology is electricity. And you say \"Wait, you don't have to do that!\"But you don't have to do that with laptops and learning either. And the fact that somebody in the room would say the impact is unclear is to me amazing - unbelievably amazing. There's not a person in this room who hasn't bought a laptop for their child, if they could afford it. And you don't know somebody who hasn't done it, if they can afford it. So there's only one question on the table and that's, “How to afford it? ” That's the only question. There is no other question - it's just the economics. And so, when One Laptop Per Child started, I didn't have the picture quite as clear as that, but we did focus on trying to get the price down. We did focus on those things. Unfortunately, Negroponte demonstrates his lack of understanding of both the history of electricity and education in this example. His historical mistake is this: yes, it was pretty obvious that electricity could bring many benefits to society. But what happened when Edison did exactly what Negroponte advocates? He almost lost his company due to his complete (but mistaken) conviction that DC, rather the AC was the correct technology to pursue. As with electricity, yes, it is rather obvious that education could bring significant benefits to the developing world. But in order to avoid making the same kind of expensive mistake that Edison did, perhaps one might want to do one’s best to make sure that the chosen technology is the AC, rather than DC, of education. A little more research, and a little less hubris might have put the investments in Edison and the OLPC to much better use. But the larger question is this: in what way is it responsible for the wealthy western world to advocate an untested and expensive (in every sense) technological solution on the poorest nations in the world? If history has taught us anything, it has taught us that just because our intentions are good, the same is not necessarily true for consequences of our actions. Later in his presentation, Negroponte states: … our problems are swimming against very naïve views of education. With this, I have to agree. It is just whose views on education are naïve, and how can such views emerge from MIT, no less, much less pass with so little critical scrutiny by the public, the press, participants, and funders? In an interview with Paul Marks, published in the New Scientist in December 2008, we see the how the techno-centric aspect of the project plays into the ostensible human centric purpose of the project. Negroponte’s retort regarding some of the initial skepticism that the project provoked was this: “When we first said we could build a laptop for $100 it was viewed as unrealistic and so 'anti-market' and so 'anti' the current laptops which at the time were around $1000 each, \" Negroponte said. \"It was viewed as pure bravado - but look what happened: the netbook market has developed in our wake. \" The project's demands for cheaper components such as keyboards, and processors nudged the industry into finding ways to cut costs, he says. \"What started off as a revolution became a culture. \"Surprise, yes, computers get smaller, faster, and cheaper over the course of time, and yes, one can even grant that the OLPC project may have accelerated that inevitable move. And, I have already stated my admiration and respect for the quality of the technology that was developed. But in the context of the overall objectives of the project, the best that one can say is, “Congratulations on meeting a milestone. ” However, by the same token, one might also legitimately question if starting with the hardware was not an instance of putting the cart before the horse. Yes, it is obviously necessary to have portable computers in the first place, before one can introduce them into the classroom, home, and donate them to children in the developing world. But it is also the case that small portable computers were already in existence and at the time that the project was initiated. While a factor of ten more expensive than the eventual target price, they were both available and adequate to support limited preliminary testing of the underlying premises of the project in an affordable manner. That is, before launching into a major - albeit well-intentioned – hardware development project, it may have been prudent to have tested the underlying premises of its motivation. Here we have to return to the raison d’être of the initiative: … to empower the world's poorest children through educationHence, the extent to which this is achieved from a given investment must be the primary metric of success, as well as the driving force of the project. Yet, that is clearly not what happened. Driven by a blind Edisonian belief in their un-tested premise, the project’s investments were overwhelmingly on the side of technology rather than pedagogy. Perhaps the nature and extent of the naïve (but well-meaning) utopian dream underlying the project is captured in the last part of the interview, above: Negroponte believes that empowering children and their parents with the educational resources offered by computers and the Internet will lead to informed decisions that improve democracy. Indeed, it has led to some gentle ribbing between himself and his brother: John Negroponte - currently deputy secretary of state in the outgoing Bush administration and the first ever director of national intelligence at the National Security Agency. \"I often joke with John that he can bring democracy his way - and I'll bring it mine, \" he says. Apparently providing inexpensive laptops to children in the developing world is not only going to raise educational standards, eradicate poverty, it is also going to bring democracy! All that, with no mention of the numerous poor non-democratic countries that have literacy levels equal to or higher than the USA (Cuba might be one reasonable example). The words naïve technological-utopianism come to mind. I began by admitting that I was conflicted in terms of this project. From the purely technological perspective, there is much to admire in the project’s accomplishments. Sadly, that was not the project’s primary objective. What appears to be missing throughout is an inability to distinguish between the technology and the purpose to which is was intended to serve. My concern in this regard is reflected in a paper by Warschauer & Ames(2010). The analysis reveals that provision of individual laptops is a utopian vision for the children in the poorest countries, whose educational and social futures could be more effectively improved if the same investments were instead made on more sustainable and proven interventions. Middle- and high-income countries may have a stronger rationale for providing individual laptops to children, but will still want to eschew OLPC’s technocentric vision. In summary, OLPC represents the latest in a long line of technologically utopian development schemes that have unsuccessfully attempted to solve complex social problems with overly simplistic solutions. There is a delicate relationship between technology and society, culture, ethics, and values. What this case study reflects is the fact that technologies are not neutral. They never are. Hence, technological initiatives must be accompanied by appropriate social, cultural and ethical considerations – especially in projects such as this where the technologies are being introduced into particularly vulnerable societies. That did not happen here, The fact that this project got the support that it did, and has gone as far as it has, given the way it was approached, is why this reminder – in the form of this device – is included in the collection. And if anyone ever wonders why I am so vocal about the need for public discourse around technology, one need look no further than the OLPC project." - } -] \ No newline at end of file diff --git a/src/scraping/buxton/json/incomplete.json b/src/scraping/buxton/json/incomplete.json deleted file mode 100644 index 4b05a2a86..000000000 --- a/src/scraping/buxton/json/incomplete.json +++ /dev/null @@ -1,468 +0,0 @@ -[ - { - "filename": "3DMag.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "3DPlus.docx", - "year": "ERR__YEAR__: outer match was captured.", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "3DSpace.docx", - "year": "ERR__YEAR__: outer match was captured.", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "3Dconnexion_SpaceNavigator.docx", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "3MErgo.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "ADB2.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "AWrock.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "Abaton.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "Active.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "AlphaSmart_Pro.docx", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured." - }, - { - "filename": "Apple_ADB_Mouse.docx", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured." - }, - { - "filename": "Apple_Mac_Portable-Katy’s MacBook Air-2.docx", - "year": "__ERR__YEAR__TRANSFORM__: NaN cannot be parsed to a numeric value.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "Apple_Mac_Portable-Katy’s MacBook Air.docx", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "Apple_Scroll_Mouse.docx", - "year": "__ERR__YEAR__TRANSFORM__: NaN cannot be parsed to a numeric value.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "Apple_iPhone.docx", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "Brailler.docx", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "Brewster_Stereoscope.docx", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "CasioTC500.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "Citizen_LC_909.docx", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "Citizen_LC_913.docx", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured." - }, - { - "filename": "Citizen_LCl_914.docx", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured." - }, - { - "filename": "CoolPix.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured." - }, - { - "filename": "Cross.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "Dymo_MK-6.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "Emotiv.docx", - "primaryKey": "ERR__PRIMARYKEY__: outer match was captured.", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "Explorer.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "Falcon.docx", - "primaryKey": "ERR__PRIMARYKEY__: outer match was captured.", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured." - }, - { - "filename": "Freeboard.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match was captured.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "FujitsuPalm.docx", - "primaryKey": "ERR__PRIMARYKEY__: outer match was captured.", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "FujitsuTouch.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured." - }, - { - "filename": "GRiD1550-Katy’s MacBook Air-2.docx", - "year": "__ERR__YEAR__TRANSFORM__: NaN cannot be parsed to a numeric value.", - "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured." - }, - { - "filename": "GRiD1550-Katy’s MacBook Air.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured." - }, - { - "filename": "GRiD1550.docx", - "primaryKey": "ERR__PRIMARYKEY__: outer match was captured.", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured." - }, - { - "filename": "Genius_Ring_Mouse.docx", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "HTC_Touch.docx", - "year": "__ERR__YEAR__TRANSFORM__: NaN cannot be parsed to a numeric value.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured." - }, - { - "filename": "Helios-Klimax.docx", - "primaryKey": "ERR__PRIMARYKEY__: outer match was captured.", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "Honeywell_T86.docx", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "IBMTrack.docx", - "year": "ERR__YEAR__: outer match was captured.", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "IBM_Convertable-Katy’s MacBook Air-2.docx", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "IBM_Convertable-Katy’s MacBook Air.docx", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "IBM_Convertable.docx", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "IBM_PS2_Mouse.docx", - "primaryKey": "ERR__PRIMARYKEY__: outer match was captured.", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "IBM_Simon.docx", - "year": "__ERR__YEAR__TRANSFORM__: NaN cannot be parsed to a numeric value." - }, - { - "filename": "IDEO.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "Joyboard.docx", - "primaryKey": "ERR__PRIMARYKEY__: outer match was captured.", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured." - }, - { - "filename": "Kensington_SB_TB-Mouse.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "Leatherman_Tread.docx", - "primaryKey": "ERR__PRIMARYKEY__: outer match was captured.", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "M1.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured." - }, - { - "filename": "MS-1_Stereoscope.docx", - "year": "__ERR__YEAR__TRANSFORM__: NaN cannot be parsed to a numeric value.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured." - }, - { - "filename": "MWB_Braille_Writer.docx", - "company": "ERR__COMPANY__: outer match wasn't captured.", - "year": "__ERR__YEAR__TRANSFORM__: NaN cannot be parsed to a numeric value.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured." - }, - { - "filename": "MaltronLH.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured." - }, - { - "filename": "Marine_Band_Harmonica.docx", - "company": "ERR__COMPANY__: outer match was captured.", - "year": "ERR__YEAR__: outer match was captured.", - "primaryKey": "ERR__PRIMARYKEY__: outer match was captured.", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "Matrox.docx", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured." - }, - { - "filename": "Metaphor_Kbd.docx", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured." - }, - { - "filename": "Metaphor_Mouse.docx", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "Motorola_DynaTAC.docx", - "year": "__ERR__YEAR__TRANSFORM__: NaN cannot be parsed to a numeric value.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "NewO.docx", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "Newton120.docx", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "Nikon_Coolpix-100.docx", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured." - }, - { - "filename": "Numonics_Mgr_Mouse.docx", - "company": "ERR__COMPANY__: outer match was captured.", - "year": "ERR__YEAR__: outer match was captured.", - "primaryKey": "ERR__PRIMARYKEY__: outer match was captured.", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "PadMouse.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "PowerTrack.docx", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "ProAgio.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "Pulsar_time_Computer.docx", - "primaryKey": "ERR__PRIMARYKEY__: outer match was captured.", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured." - }, - { - "filename": "Ring.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "SafeType_Kbd.docx", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured." - }, - { - "filename": "Samsung_SPH-A500.docx", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "SurfMouse.docx", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured." - }, - { - "filename": "TPARCtab.docx", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "Thumbelina.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured." - }, - { - "filename": "adecm.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "eMate.docx", - "primaryKey": "ERR__PRIMARYKEY__: outer match was captured.", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "gravis.docx", - "year": "ERR__YEAR__: outer match was captured.", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "iGesture.docx", - "year": "__ERR__YEAR__TRANSFORM__: NaN cannot be parsed to a numeric value.", - "primaryKey": "ERR__PRIMARYKEY__: outer match was captured.", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "iGrip.docx", - "shortDescription": "ERR__SHORTDESCRIPTION__: outer match was captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - }, - { - "filename": "iLiad.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "degreesOfFreedom": "ERR__DEGREESOFFREEDOM__: outer match wasn't captured." - }, - { - "filename": "round.docx", - "secondaryKey": "ERR__SECONDARYKEY__: outer match wasn't captured.", - "originalPrice": "ERR__ORIGINALPRICE__: outer match wasn't captured.", - "dimensions": "ERR__DIMENSIONS__: outer match wasn't captured.", - "longDescription": "ERR__LONGDESCRIPTION__: outer match was captured." - } -] \ No newline at end of file diff --git a/src/scraping/buxton/node_scraper.ts b/src/scraping/buxton/node_scraper.ts deleted file mode 100644 index ab6c9dcb2..000000000 --- a/src/scraping/buxton/node_scraper.ts +++ /dev/null @@ -1,256 +0,0 @@ -import { readdirSync, writeFile, existsSync, mkdirSync } from "fs"; -import * as path from "path"; -import { red, cyan, yellow, green } from "colors"; -import { Opt } from "../../new_fields/Doc"; -const StreamZip = require('node-stream-zip'); - -export interface DeviceDocument { - title: string; - shortDescription: string; - longDescription: string; - company: string; - year: number; - originalPrice: number; - degreesOfFreedom: number; - dimensions: string; - primaryKey: string; - secondaryKey: string; -} - -interface AnalysisResult { - device?: DeviceDocument; - errors?: any; -} - -type Converter = (raw: string) => { transformed?: T, error?: string }; - -interface Processor { - exp: RegExp; - matchIndex?: number; - transformer?: Converter; -} - -const RegexMap = new Map>([ - ["title", { - exp: /contact\s+(.*)Short Description:/ - }], - ["company", { - exp: /Company:\s+([^\|]*)\s+\|/, - transformer: (raw: string) => ({ transformed: raw.replace(/\./g, "") }) - }], - ["year", { - exp: /Year:\s+([^\|]*)\s+\|/, - transformer: numberValue - }], - ["primaryKey", { - exp: /Primary:\s+(.*)(Secondary|Additional):/, - transformer: collectUniqueTokens - }], - ["secondaryKey", { - exp: /(Secondary|Additional):\s+([^\{\}]*)Links/, - transformer: collectUniqueTokens, - matchIndex: 2 - }], - ["originalPrice", { - exp: /Original Price \(USD\)\:\s+\$([0-9\.]+)/, - transformer: numberValue - }], - ["degreesOfFreedom", { - exp: /Degrees of Freedom:\s+([0-9]+)/, - transformer: numberValue - }], - ["dimensions", { - exp: /Dimensions\s+\(L x W x H\):\s+([0-9\.]+\s+x\s+[0-9\.]+\s+x\s+[0-9\.]+\s\([A-Za-z]+\))/, - transformer: (raw: string) => { - const [length, width, group] = raw.split(" x "); - const [height, unit] = group.split(" "); - return { - transformed: { - length: Number(length), - width: Number(width), - height: Number(height), - unit: unit.replace(/[\(\)]+/g, "") - } - }; - } - }], - ["shortDescription", { - exp: /Short Description:\s+(.*)Bill Buxton[’']s Notes/, - transformer: correctSentences - }], - ["longDescription", { - exp: /Bill Buxton[’']s Notes(.*)Device Details/, - transformer: correctSentences - }], -]); - -function numberValue(raw: string) { - const transformed = Number(raw); - if (isNaN(transformed)) { - return { error: `${transformed} cannot be parsed to a numeric value.` }; - } - return { transformed }; -} - -function collectUniqueTokens(raw: string) { - return { transformed: Array.from(new Set(raw.replace(/,|\s+and\s+/g, " ").split(/\s+/).map(token => token.toLowerCase().trim()))).map(capitalize).sort() }; -} - -function correctSentences(raw: string) { - raw = raw.replace(/\./g, ". ").replace(/\:/g, ": ").replace(/\,/g, ", ").replace(/\?/g, "? ").trimRight(); - raw = raw.replace(/\s{2,}/g, " "); - return { transformed: raw }; -} - -const outDir = path.resolve(__dirname, "json"); -const successOut = "buxton.json"; -const failOut = "incomplete.json"; -const deviceKeys = Array.from(RegexMap.keys()); - -function printEntries(zip: any) { - const { entriesCount } = zip; - console.log(`Recognized ${entriesCount} entr${entriesCount === 1 ? "y" : "ies"}.`); - for (const entry of Object.values(zip.entries())) { - const desc = entry.isDirectory ? 'directory' : `${entry.size} bytes`; - console.log(`${entry.name}: ${desc}`); - } -} - -async function wordToPlainText(pathToDocument: string): Promise { - const zip = new StreamZip({ file: pathToDocument, storeEntries: true }); - const contents = await new Promise((resolve, reject) => { - zip.on('ready', () => { - let body = ""; - zip.stream("word/document.xml", (error: any, stream: any) => { - if (error) { - reject(error); - } - stream.on('data', (chunk: any) => body += chunk.toString()); - stream.on('end', () => { - resolve(body); - zip.close(); - }); - }); - }); - }); - let body = ""; - const components = contents.toString().split(''); - const content = tags[1].replace(/<.*$/, ""); - body += content; - } - return body; -} - -function tryGetValidCapture(matches: RegExpExecArray | null, matchIndex: number): Opt { - let captured: string; - if (!matches || !(captured = matches[matchIndex])) { - return undefined; - } - const lower = captured.toLowerCase(); - if (/to come/.test(lower)) { - return undefined; - } - if (lower.includes("xxx")) { - return undefined; - } - if (!captured.toLowerCase().replace(/[….\s]+/g, "").length) { - return undefined; - } - return captured; -} - -function capitalize(word: string): string { - const clean = word.trim(); - if (!clean.length) { - return word; - } - return word.charAt(0).toUpperCase() + word.slice(1); -} - -function analyze(path: string, body: string): AnalysisResult { - const device: any = {}; - - const segments = path.split("/"); - const filename = segments[segments.length - 1].replace("Bill_Notes_", ""); - - const errors: any = { filename }; - - for (const key of deviceKeys) { - const { exp, transformer, matchIndex } = RegexMap.get(key)!; - const matches = exp.exec(body); - - let captured = tryGetValidCapture(matches, matchIndex ?? 1); - if (!captured) { - errors[key] = `ERR__${key.toUpperCase()}__: outer match ${matches === null ? "wasn't" : "was"} captured.`; - continue; - } - - captured = captured.replace(/\s{2,}/g, " "); - if (transformer) { - const { error, transformed } = transformer(captured); - if (error) { - errors[key] = `__ERR__${key.toUpperCase()}__TRANSFORM__: ${error}`; - continue; - } - captured = transformed; - } - - device[key] = captured; - } - - const errorKeys = Object.keys(errors); - if (errorKeys.length > 1) { - console.log(red(`\n@ ${cyan(filename.toUpperCase())}...`)); - errorKeys.forEach(key => key !== "filename" && console.log(red(errors[key]))); - return { errors }; - } - - return { device }; -} - -async function parseFiles(): Promise { - const sourceDirectory = path.resolve(`${__dirname}/source`); - const candidates = readdirSync(sourceDirectory).filter(file => file.endsWith(".doc") || file.endsWith(".docx")).map(file => `${sourceDirectory}/${file}`); - const imported = await Promise.all(candidates.map(async path => ({ path, body: await wordToPlainText(path) }))); - // const imported = [{ path: candidates[10], body: await extract(candidates[10]) }]; - const data = imported.map(({ path, body }) => analyze(path, body)); - const masterDevices: DeviceDocument[] = []; - const masterErrors: any[] = []; - data.forEach(({ device, errors }) => { - if (device) { - masterDevices.push(device); - } else { - masterErrors.push(errors); - } - }); - const total = candidates.length; - if (masterDevices.length + masterErrors.length !== total) { - throw new Error(`Encountered a ${masterDevices.length} to ${masterErrors.length} mismatch in device / error split!`); - } - console.log(); - await writeOutputFile(successOut, masterDevices, total, true); - await writeOutputFile(failOut, masterErrors, total, false); - console.log(); - - return masterDevices; -} - -async function writeOutputFile(relativePath: string, data: any[], total: number, success: boolean) { - console.log(yellow(`Encountered ${data.length} ${success ? "valid" : "invalid"} documents out of ${total} candidates. Writing ${relativePath}...`)); - return new Promise((resolve, reject) => { - const destination = path.resolve(outDir, relativePath); - const contents = JSON.stringify(data, undefined, 4); - writeFile(destination, contents, err => err ? reject(err) : resolve()); - }); -} - -export async function main() { - if (!existsSync(outDir)) { - mkdirSync(outDir); - } - return parseFiles(); -} - -main(); \ No newline at end of file diff --git a/src/server/ApiManagers/UtilManager.ts b/src/server/ApiManagers/UtilManager.ts index dbf274e93..e590a5b85 100644 --- a/src/server/ApiManagers/UtilManager.ts +++ b/src/server/ApiManagers/UtilManager.ts @@ -4,7 +4,7 @@ import { exec } from 'child_process'; import { command_line } from "../ActionUtilities"; import RouteSubscriber from "../RouteSubscriber"; import { red } from "colors"; -import { main } from "../../scraping/buxton/node_scraper"; +import executeImport from "../../scraping/buxton/final/BuxtonImporter"; export default class UtilManager extends ApiManager { @@ -40,29 +40,29 @@ export default class UtilManager extends ApiManager { } }); - register({ - method: Method.GET, - subscription: "/buxton", - secureHandler: async ({ res }) => { - const cwd = './src/scraping/buxton'; + // register({ + // method: Method.GET, + // subscription: "/buxton", + // secureHandler: async ({ res }) => { + // const cwd = './src/scraping/buxton'; - const onResolved = (stdout: string) => { console.log(stdout); res.redirect("/"); }; - const onRejected = (err: any) => { console.error(err.message); res.send(err); }; - const tryPython3 = (reason: any) => { - console.log("Initial scraper failed for the following reason:"); - console.log(red(reason.Error)); - console.log("Falling back to python3..."); - return command_line('python3 scraper.py', cwd).then(onResolved, onRejected); - }; + // const onResolved = (stdout: string) => { console.log(stdout); res.redirect("/"); }; + // const onRejected = (err: any) => { console.error(err.message); res.send(err); }; + // const tryPython3 = (reason: any) => { + // console.log("Initial scraper failed for the following reason:"); + // console.log(red(reason.Error)); + // console.log("Falling back to python3..."); + // return command_line('python3 scraper.py', cwd).then(onResolved, onRejected); + // }; - return command_line('python scraper.py', cwd).then(onResolved, tryPython3); - }, - }); + // return command_line('python scraper.py', cwd).then(onResolved, tryPython3); + // }, + // }); register({ method: Method.GET, - subscription: "/newBuxton", - secureHandler: async ({ res }) => res.send(await main()) + subscription: "/buxton", + secureHandler: async ({ res }) => res.send(await executeImport()) }); register({ diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 71775bed6..896b88631 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -58,7 +58,7 @@ export class CurrentUserUtils { { title: "todo item", icon: "check", ignoreClick: true, drag: 'getCopy(this.dragFactory, true)', dragFactory: notes[notes.length - 1] }, { title: "web page", icon: "globe-asia", ignoreClick: true, drag: 'Docs.Create.WebDocument("https://en.wikipedia.org/wiki/Hedgehog", {_width: 300, _height: 300, title: "New Webpage" })' }, { title: "cat image", icon: "cat", ignoreClick: true, drag: 'Docs.Create.ImageDocument("https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg", { _width: 200, title: "an image of a cat" })' }, - { title: "buxton", icon: "faObjectGroup", ignoreClick: true, drag: "Docs.Create.Buxton()" }, + { title: "buxton", icon: "cloud-upload-alt", ignoreClick: true, drag: "Docs.Create.Buxton()" }, { title: "record", icon: "microphone", ignoreClick: true, drag: `Docs.Create.AudioDocument("${nullAudio}", { _width: 200, title: "ready to record audio" })` }, { title: "clickable button", icon: "bolt", ignoreClick: true, drag: 'Docs.Create.ButtonDocument({ _width: 150, _height: 50, title: "Button" })' }, { title: "presentation", icon: "tv", click: 'openOnRight(Doc.UserDoc().curPresentation = getCopy(this.dragFactory, true))', drag: `Doc.UserDoc().curPresentation = getCopy(this.dragFactory,true)`, dragFactory: emptyPresentation }, -- cgit v1.2.3-70-g09d2 From 28efd6f2b5b79d1f25fa66e5d9f69d77a7594fee Mon Sep 17 00:00:00 2001 From: vellichora Date: Sat, 8 Feb 2020 20:48:51 -0500 Subject: refactored mobile interface so that current views are created via scripting --- src/client/views/nodes/WebBox.tsx | 6 +- src/mobile/ImageUpload.tsx | 10 +- src/mobile/MobileInkOverlay.tsx | 6 +- src/mobile/MobileInterface.tsx | 115 +++++++++++++-------- .../authentication/models/current_user_utils.ts | 13 ++- 5 files changed, 92 insertions(+), 58 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/views/nodes/WebBox.tsx b/src/client/views/nodes/WebBox.tsx index b35ea0bb0..0b23c3bec 100644 --- a/src/client/views/nodes/WebBox.tsx +++ b/src/client/views/nodes/WebBox.tsx @@ -182,9 +182,11 @@ export class WebBox extends DocAnnotatableComponent {view}
; - const frozen = !this.props.isSelected() || DocumentDecorations.Instance.Interacting; + const decInteracting = DocumentDecorations.Instance && DocumentDecorations.Instance.Interacting; - const classname = "webBox-cont" + (this.props.isSelected() && InkingControl.Instance.selectedTool === InkTool.None && !DocumentDecorations.Instance.Interacting ? "-interactive" : ""); + const frozen = !this.props.isSelected() || decInteracting; + + const classname = "webBox-cont" + (this.props.isSelected() && InkingControl.Instance.selectedTool === InkTool.None && !decInteracting ? "-interactive" : ""); return ( <>
diff --git a/src/mobile/ImageUpload.tsx b/src/mobile/ImageUpload.tsx index 0b0280519..3304e8e22 100644 --- a/src/mobile/ImageUpload.tsx +++ b/src/mobile/ImageUpload.tsx @@ -13,6 +13,7 @@ import { observable } from 'mobx'; import { Utils } from '../Utils'; import MobileInterface from './MobileInterface'; import { CurrentUserUtils } from '../server/authentication/models/current_user_utils'; +import { Scripting } from '../client/util/Scripting'; @@ -27,12 +28,11 @@ const inputRef = React.createRef(); @observer class Uploader extends React.Component { - @observable - error: string = ""; - @observable - status: string = ""; + @observable error: string = ""; + @observable status: string = ""; onClick = async () => { + console.log("uploader click"); try { this.status = "initializing protos"; await Docs.Prototypes.initialize(); @@ -105,6 +105,8 @@ class Uploader extends React.Component { } +// Scripting.addGlobal(function uploadImageMobile() { return Uploader.onClick(); }); + // DocServer.init(window.location.protocol, window.location.hostname, 4321, "image upload"); (async () => { diff --git a/src/mobile/MobileInkOverlay.tsx b/src/mobile/MobileInkOverlay.tsx index 600e8a91b..6b65aa436 100644 --- a/src/mobile/MobileInkOverlay.tsx +++ b/src/mobile/MobileInkOverlay.tsx @@ -37,9 +37,9 @@ export default class MobileInkOverlay extends React.Component { initMobileInkOverlay(content: MobileInkOverlayContent) { const { width, height } = content; const scaledSize = this.initialSize(width ? width : 0, height ? height : 0); - this._width = scaledSize.width * .8; - this._height = scaledSize.height * .8; - this._scale = .8; //scaledSize.scale; + this._width = scaledSize.width; + this._height = scaledSize.height; + this._scale = scaledSize.scale; //scaledSize.scale; this._x = 300; // TODO: center on screen this._y = 25; // TODO: center on screen } diff --git a/src/mobile/MobileInterface.tsx b/src/mobile/MobileInterface.tsx index 03bcbca80..665d9a168 100644 --- a/src/mobile/MobileInterface.tsx +++ b/src/mobile/MobileInterface.tsx @@ -30,14 +30,14 @@ export default class MobileInterface extends React.Component { @observable static Instance: MobileInterface; @computed private get userDoc() { return CurrentUserUtils.UserDocument; } @computed private get mainContainer() { return this.userDoc ? FieldValue(Cast(this.userDoc.activeMobile, Doc)) : CurrentUserUtils.GuestMobile; } - @observable private currentView: "main" | "ink" | "upload" = "main"; + // @observable private currentView: "main" | "ink" | "upload" = "main"; + private mainDoc: Doc = CurrentUserUtils.setupMobileDoc(this.userDoc); + @observable private renderView?: () => JSX.Element; - private mainDoc = CurrentUserUtils.setupMobileDoc(this.userDoc); - - private inkDoc?: Doc; + // private inkDoc?: Doc; public drawingInk: boolean = false; - private uploadDoc?: Doc; + // private uploadDoc?: Doc; constructor(props: Readonly<{}>) { super(props); @@ -55,41 +55,63 @@ export default class MobileInterface extends React.Component { } @action - switchCurrentView = (view: "main" | "ink" | "upload") => { - this.currentView = view; + switchCurrentView = (doc: (userDoc: Doc) => Doc, renderView?: () => JSX.Element, onSwitch?: () => void) => { + if (!this.userDoc) return; - if (this.userDoc) { - switch (view) { - case "main": { - // const doc = CurrentUserUtils.setupMobileDoc(this.userDoc); - this.userDoc.activeMobile = this.mainDoc; - break; - } - case "ink": { - this.inkDoc = CurrentUserUtils.setupMobileInkingDoc(this.userDoc); - this.userDoc.activeMobile = this.inkDoc; - InkingControl.Instance.switchTool(InkTool.Pen); - this.drawingInk = true; + this.userDoc.activeMobile = doc(this.userDoc); + onSwitch && onSwitch(); - DocServer.Mobile.dispatchOverlayTrigger({ - enableOverlay: true, - width: window.innerWidth, - height: window.innerHeight - }); + this.renderView = renderView; + console.log("switching current view", renderView); + } - break; - } - case "upload": { - this.uploadDoc = CurrentUserUtils.setupMobileUploadDoc(this.userDoc); - this.userDoc.activeMobile = this.uploadDoc; + onSwitchInking = () => { + InkingControl.Instance.switchTool(InkTool.Pen); + MobileInterface.Instance.drawingInk = true; - } - } - } + DocServer.Mobile.dispatchOverlayTrigger({ + enableOverlay: true, + width: window.innerWidth, + height: window.innerHeight + }); } - @computed - get mainContent() { + // @action + // switchCurrentView = (view: "main" | "ink" | "upload") => { + // this.currentView = view; + + // if (this.userDoc) { + // switch (view) { + // case "main": { + // // const doc = CurrentUserUtils.setupMobileDoc(this.userDoc); + // this.userDoc.activeMobile = this.mainDoc; + // break; + // } + // case "ink": { + // this.inkDoc = CurrentUserUtils.setupMobileInkingDoc(this.userDoc); + // this.userDoc.activeMobile = this.inkDoc; + // InkingControl.Instance.switchTool(InkTool.Pen); + // this.drawingInk = true; + + // DocServer.Mobile.dispatchOverlayTrigger({ + // enableOverlay: true, + // width: window.innerWidth, + // height: window.innerHeight + // }); + + // break; + // } + // case "upload": { + // this.uploadDoc = CurrentUserUtils.setupMobileUploadDoc(this.userDoc); + // this.userDoc.activeMobile = this.uploadDoc; + + // } + // } + // } + // } + + renderDefaultContent = () => { + console.log("rendering default content"); if (this.mainContainer) { return { - this.switchCurrentView("main"); + this.switchCurrentView((userDoc: Doc) => this.mainDoc); InkingControl.Instance.switchTool(InkTool.None); // TODO: switch to previous tool DocServer.Mobile.dispatchOverlayTrigger({ @@ -130,7 +152,7 @@ export default class MobileInterface extends React.Component { height: window.innerHeight }); - this.inkDoc = undefined; + // this.inkDoc = undefined; this.drawingInk = false; } @@ -151,8 +173,8 @@ export default class MobileInterface extends React.Component { e.stopPropagation(); } - @computed - get inkContent() { + renderInkingContent = () => { + console.log("rendering inking content"); // TODO: support panning and zooming // TODO: handle moving of ink strokes if (this.mainContainer) { @@ -202,8 +224,7 @@ export default class MobileInterface extends React.Component { } - @computed - get uploadContent() { + renderUploadContent() { if (this.mainContainer) { return (
@@ -246,15 +267,19 @@ export default class MobileInterface extends React.Component { } render() { - const content = this.currentView === "main" ? this.mainContent : - this.currentView === "ink" ? this.inkContent : - this.currentView === "upload" ? this.uploadContent : <>; + // const content = this.currentView === "main" ? this.mainContent : + // this.currentView === "ink" ? this.inkContent : + // this.currentView === "upload" ? this.uploadContent : <>; return (
- {content} + {this.renderView ? this.renderView() : this.renderDefaultContent()}
); } } -Scripting.addGlobal(function switchMobileView(view: "main" | "ink" | "upload") { return MobileInterface.Instance.switchCurrentView(view); }); +Scripting.addGlobal(function switchMobileView(doc: (userDoc: Doc) => Doc, renderView?: () => JSX.Element, onSwitch?: () => void) { return MobileInterface.Instance.switchCurrentView(doc, renderView, onSwitch); }); +Scripting.addGlobal(function onSwitchMobileInking() { return MobileInterface.Instance.onSwitchInking(); }); +Scripting.addGlobal(function renderMobileInking() { return MobileInterface.Instance.renderInkingContent(); }); +Scripting.addGlobal(function renderMobileUpload() { return MobileInterface.Instance.renderUploadContent(); }); + diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 82bed76f7..817cf40b1 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -14,6 +14,7 @@ import { Utils } from "../../../Utils"; import { nullAudio } from "../../../new_fields/URLField"; import { DragManager } from "../../../client/util/DragManager"; import { InkingControl } from "../../../client/views/InkingControl"; +import { Scripting } from "../../../client/util/Scripting"; export class CurrentUserUtils { private static curr_id: string; @@ -101,8 +102,9 @@ export class CurrentUserUtils { { title: "use eraser", icon: "eraser", click: 'activateEraser(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "pink", activePen: doc }, { title: "use scrubber", icon: "eraser", click: 'activateScrubber(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "green", activePen: doc }, { title: "use drag", icon: "mouse-pointer", click: 'deactivateInk();this.activePen.pen = this;', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "white", activePen: doc }, - { title: "draw", icon: "pen-nib", click: 'switchMobileView("ink");', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "red", activePen: doc }, - { title: "upload", icon: "upload", click: 'switchMobileView("upload");', backgroundColor: "orange" }, + { title: "draw", icon: "pen-nib", click: 'switchMobileView(setupMobileInkingDoc, renderMobileInking, onSwitchMobileInking);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "red", activePen: doc }, + { title: "upload", icon: "upload", click: 'switchMobileView(setupMobileUploadDoc, renderMobileUpload);', backgroundColor: "orange" }, + { title: "upload", icon: "upload", click: 'uploadImageMobile();', backgroundColor: "cyan" }, ]; return docProtoData.filter(d => !buttons || !buttons.includes(d.title)).map(data => Docs.Create.FontIconDocument({ nativeWidth: 100, nativeHeight: 100, width: 100, height: 100, dropAction: data.click ? "copy" : undefined, title: data.title, icon: data.icon, ignoreClick: data.ignoreClick, @@ -147,7 +149,7 @@ export class CurrentUserUtils { static setupMobileUploadDoc(userDoc: Doc) { console.log("setup mobile upload", window.innerWidth, window.innerHeight); - const webDoc = Docs.Create.WebDocument("https://wikipedia.com", { title: "Mobile Upload Web", chromeStatus: "enabled", ignoreClick: true }); + const webDoc = Docs.Create.WebDocument("https://wikipedia.com", { title: "Mobile Upload Web", chromeStatus: "enabled" }); const uploadDoc = Docs.Create.StackingDocument([], { title: "Mobile Upload", backgroundColor: "pink" }); return Docs.Create.StackingDocument([webDoc, uploadDoc], { title: "Mobile Upload", backgroundColor: "white", @@ -388,4 +390,7 @@ export class CurrentUserUtils { }; return recurs([] as Attribute[], schema ? schema.rootAttributeGroup : undefined); } -} \ No newline at end of file +} + +Scripting.addGlobal(function setupMobileInkingDoc(userDoc: Doc) { return CurrentUserUtils.setupMobileInkingDoc(userDoc); }); +Scripting.addGlobal(function setupMobileUploadDoc(userDoc: Doc) { return CurrentUserUtils.setupMobileUploadDoc(userDoc); }); \ No newline at end of file -- cgit v1.2.3-70-g09d2 From e8fcbbf57b2a2f443d9c280ce10558cf9d51c632 Mon Sep 17 00:00:00 2001 From: vellichora Date: Sun, 9 Feb 2020 17:11:24 -0500 Subject: can upload collection from mobile to desktop --- src/client/DocServer.ts | 9 +- src/client/util/DragManager.ts | 2 +- .../collections/CollectionMasonryViewFieldRow.tsx | 1 + .../views/collections/CollectionStackingView.tsx | 2 + .../CollectionStackingViewFieldColumn.tsx | 1 + src/client/views/collections/CollectionSubView.tsx | 2 +- src/client/views/collections/CollectionView.tsx | 2 +- .../views/collections/CollectionViewChromes.tsx | 1 + src/mobile/ImageUpload.tsx | 1 + src/mobile/MobileInkOverlay.tsx | 53 +++++++- src/mobile/MobileInterface.scss | 8 ++ src/mobile/MobileInterface.tsx | 150 ++++++++++++--------- src/server/ApiManagers/UploadManager.ts | 1 + src/server/Message.ts | 6 + src/server/Websocket/Websocket.ts | 7 +- .../authentication/models/current_user_utils.ts | 21 +-- src/server/server_Initialization.ts | 24 ++-- 17 files changed, 195 insertions(+), 96 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/DocServer.ts b/src/client/DocServer.ts index c03764471..e09251855 100644 --- a/src/client/DocServer.ts +++ b/src/client/DocServer.ts @@ -1,5 +1,5 @@ import * as OpenSocket from 'socket.io-client'; -import { MessageStore, YoutubeQueryTypes, GestureContent, MobileInkOverlayContent, UpdateMobileInkOverlayPositionContent } from "./../server/Message"; +import { MessageStore, YoutubeQueryTypes, GestureContent, MobileInkOverlayContent, UpdateMobileInkOverlayPositionContent, MobileDocumentUploadContent } from "./../server/Message"; import { Opt, Doc } from '../new_fields/Doc'; import { Utils, emptyFunction } from '../Utils'; import { SerializationHelper } from './util/SerializationHelper'; @@ -81,6 +81,10 @@ export namespace DocServer { Utils.Emit(_socket, MessageStore.UpdateMobileInkOverlayPosition, content); } + export function dispatchMobileDocumentUpload(content: MobileDocumentUploadContent) { + Utils.Emit(_socket, MessageStore.MobileDocumentUpload, content); + } + } export function init(protocol: string, hostname: string, port: number, identifier: string) { @@ -116,6 +120,9 @@ export namespace DocServer { _socket.addEventListener("receiveUpdateOverlayPosition", (content: UpdateMobileInkOverlayPositionContent) => { MobileInkOverlay.Instance.updatePosition(content); }); + _socket.addEventListener("receiveMobileDocumentUpload", (content: MobileDocumentUploadContent) => { + MobileInkOverlay.Instance.uploadDocument(content); + }); } function errorFunc(): never { diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index df2f5fe3c..0bb8b531d 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -179,7 +179,7 @@ export namespace DragManager { ); } element.dataset.canDrop = "true"; - const handler = (e: Event) => dropFunc(e, (e as CustomEvent).detail); + const handler = (e: Event) => { console.log("drop target reveied docs"); dropFunc(e, (e as CustomEvent).detail); }; element.addEventListener("dashOnDrop", handler); return () => { element.removeEventListener("dashOnDrop", handler); diff --git a/src/client/views/collections/CollectionMasonryViewFieldRow.tsx b/src/client/views/collections/CollectionMasonryViewFieldRow.tsx index 80752303c..26e0cc35a 100644 --- a/src/client/views/collections/CollectionMasonryViewFieldRow.tsx +++ b/src/client/views/collections/CollectionMasonryViewFieldRow.tsx @@ -73,6 +73,7 @@ export class CollectionMasonryViewFieldRow extends React.Component { + console.log("masronry row drop"); this._createAliasSelected = false; if (de.complete.docDragData) { (this.props.parent.Document.dropConverter instanceof ScriptField) && diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index 992820fc7..83c90810e 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -240,6 +240,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { @undoBatch @action drop = (e: Event, de: DragManager.DropEvent) => { + console.log("DROP STACKIN G2"); const where = [de.x, de.y]; let targInd = -1; let plusOne = 0; @@ -270,6 +271,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { @undoBatch @action onDrop = async (e: React.DragEvent): Promise => { + console.log("DROP STACKING"); const where = [e.clientX, e.clientY]; let targInd = -1; this._docXfs.map((cd, i) => { diff --git a/src/client/views/collections/CollectionStackingViewFieldColumn.tsx b/src/client/views/collections/CollectionStackingViewFieldColumn.tsx index 39b4e4e1d..65c4b3195 100644 --- a/src/client/views/collections/CollectionStackingViewFieldColumn.tsx +++ b/src/client/views/collections/CollectionStackingViewFieldColumn.tsx @@ -57,6 +57,7 @@ export class CollectionStackingViewFieldColumn extends React.Component { + console.log("column drop stacking"); this._createAliasSelected = false; if (de.complete.docDragData) { const key = StrCast(this.props.parent.props.Document.sectionFilter); diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index e94f24f2c..b35af2314 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -6,7 +6,7 @@ import { Id } from "../../../new_fields/FieldSymbols"; import { List } from "../../../new_fields/List"; import { listSpec } from "../../../new_fields/Schema"; import { ScriptField } from "../../../new_fields/ScriptField"; -import { Cast } from "../../../new_fields/Types"; +import { Cast, StrCast } from "../../../new_fields/Types"; import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; import { Utils } from "../../../Utils"; import { DocServer } from "../../DocServer"; diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index 88023783b..1d399e26f 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -138,7 +138,7 @@ export class CollectionView extends Touchable { let index = value.reduce((p, v, i) => (v instanceof Doc && v === doc) ? i : p, -1); index = index !== -1 ? index : value.reduce((p, v, i) => (v instanceof Doc && Doc.AreProtosEqual(v, doc)) ? i : p, -1); - ContextMenu.Instance.clearItems(); + ContextMenu.Instance && ContextMenu.Instance.clearItems(); if (index !== -1) { value.splice(index, 1); return true; diff --git a/src/client/views/collections/CollectionViewChromes.tsx b/src/client/views/collections/CollectionViewChromes.tsx index a870b6043..01dc21f95 100644 --- a/src/client/views/collections/CollectionViewChromes.tsx +++ b/src/client/views/collections/CollectionViewChromes.tsx @@ -231,6 +231,7 @@ export class CollectionViewBaseChrome extends React.Component { + console.log("toggle collapse"); this.props.CollectionView.props.Document.chromeStatus = this.props.CollectionView.props.Document.chromeStatus === "enabled" ? "collapsed" : "enabled"; if (this.props.collapse) { this.props.collapse(this.props.CollectionView.props.Document.chromeStatus !== "enabled"); diff --git a/src/mobile/ImageUpload.tsx b/src/mobile/ImageUpload.tsx index 3304e8e22..10bd78075 100644 --- a/src/mobile/ImageUpload.tsx +++ b/src/mobile/ImageUpload.tsx @@ -47,6 +47,7 @@ class Uploader extends React.Component { const upload = window.location.origin + "/upload"; this.status = "uploading image"; + console.log("uploading image", formData); const res = await fetch(upload, { method: 'POST', body: formData diff --git a/src/mobile/MobileInkOverlay.tsx b/src/mobile/MobileInkOverlay.tsx index 6b65aa436..ed4cca5b9 100644 --- a/src/mobile/MobileInkOverlay.tsx +++ b/src/mobile/MobileInkOverlay.tsx @@ -1,9 +1,13 @@ import React = require('react'); import { observer } from "mobx-react"; -import { MobileInkOverlayContent, GestureContent, UpdateMobileInkOverlayPositionContent } from "../server/Message"; +import { MobileInkOverlayContent, GestureContent, UpdateMobileInkOverlayPositionContent, MobileDocumentUploadContent } from "../server/Message"; import { observable, action } from "mobx"; import { GestureUtils } from "../pen-gestures/GestureUtils"; import "./MobileInkOverlay.scss"; +import { StrCast } from '../new_fields/Types'; +import { DragManager } from "../client/util/DragManager"; +import { DocServer } from '../client/DocServer'; +import { Doc } from '../new_fields/Doc'; @observer @@ -67,7 +71,7 @@ export default class MobileInkOverlay extends React.Component { height: bounds.height * this._scale, }; - const target = document.elementFromPoint(points[0].X, points[0].Y); + const target = document.elementFromPoint(this._x + 10, this._y + 10); target?.dispatchEvent( new CustomEvent("dashOnGesture", { @@ -82,6 +86,43 @@ export default class MobileInkOverlay extends React.Component { ); } + uploadDocument = async (content: MobileDocumentUploadContent) => { + const { docId } = content; + console.log("receive upload document id", docId); + const doc = await DocServer.GetRefField(docId); + + if (doc && doc instanceof Doc) { + console.log("parsed upload document into doc", StrCast(doc.proto!.title)); + + const target = document.elementFromPoint(this._x + 10, this._y + 10); + console.log("the target is", target); + + const dragData = new DragManager.DocumentDragData([doc]); + const complete = new DragManager.DragCompleteEvent(false, dragData); + console.log("the drag data is", dragData); + + if (target) { + target.dispatchEvent( + new CustomEvent("dashOnDrop", + { + bubbles: true, + detail: { + x: this._x, + y: this._y, + complete: complete, + altKey: false, + metaKey: false, + ctrlKey: false + } + } + ) + ); + } else { + alert("TARGET IS UNDEFINED"); + } + } + } + @action dragStart = (e: React.PointerEvent) => { document.removeEventListener("pointermove", this.dragging); @@ -132,15 +173,17 @@ export default class MobileInkOverlay extends React.Component { transform: `translate(${this._x}px, ${this._y}px)`, zIndex: 30000, pointerEvents: "none", - borderStyle: this._isDragging ? "solid" : "dashed" - }} + borderStyle: this._isDragging ? "solid" : "dashed", + backgroundColor: "rgba(255, 0, 0, 0.3)" + } + } ref={this._mainCont} >
-
+
); } } \ No newline at end of file diff --git a/src/mobile/MobileInterface.scss b/src/mobile/MobileInterface.scss index 8abe5a40d..8b0ebcd53 100644 --- a/src/mobile/MobileInterface.scss +++ b/src/mobile/MobileInterface.scss @@ -1,7 +1,15 @@ .mobileInterface-inkInterfaceButtons { position: absolute; + top: -50px; display: flex; justify-content: space-between; width: 100%; z-index: 9999; + height: 50px; +} + +.mobileInterface-container { + height: calc(100% - 50px); + margin-top: 50px; + position: relative; } \ No newline at end of file diff --git a/src/mobile/MobileInterface.tsx b/src/mobile/MobileInterface.tsx index 665d9a168..a1ef0a5d1 100644 --- a/src/mobile/MobileInterface.tsx +++ b/src/mobile/MobileInterface.tsx @@ -22,6 +22,18 @@ import { SelectionManager } from '../client/util/SelectionManager'; import { DateField } from '../new_fields/DateField'; import { GestureUtils } from '../pen-gestures/GestureUtils'; import { DocServer } from '../client/DocServer'; +import { DocumentDecorations } from '../client/views/DocumentDecorations'; +import { OverlayView } from '../client/views/OverlayView'; +import { DictationOverlay } from '../client/views/DictationOverlay'; +import SharingManager from '../client/util/SharingManager'; +import { PreviewCursor } from '../client/views/PreviewCursor'; +import { ContextMenu } from '../client/views/ContextMenu'; +import { RadialMenu } from '../client/views/nodes/RadialMenu'; +import PDFMenu from '../client/views/pdf/PDFMenu'; +import MarqueeOptionsMenu from '../client/views/collections/collectionFreeForm/MarqueeOptionsMenu'; +import GoogleAuthenticationManager from '../client/apis/GoogleAuthenticationManager'; +import { listSpec } from '../new_fields/Schema'; +import { Id } from '../new_fields/FieldSymbols'; library.add(faLongArrowAltLeft); @@ -31,7 +43,7 @@ export default class MobileInterface extends React.Component { @computed private get userDoc() { return CurrentUserUtils.UserDocument; } @computed private get mainContainer() { return this.userDoc ? FieldValue(Cast(this.userDoc.activeMobile, Doc)) : CurrentUserUtils.GuestMobile; } // @observable private currentView: "main" | "ink" | "upload" = "main"; - private mainDoc: Doc = CurrentUserUtils.setupMobileDoc(this.userDoc); + private mainDoc: any = CurrentUserUtils.setupMobileDoc(this.userDoc); @observable private renderView?: () => JSX.Element; // private inkDoc?: Doc; @@ -49,7 +61,6 @@ export default class MobileInterface extends React.Component { library.add(...[faPenNib, faHighlighter, faEraser, faMousePointer]); if (this.userDoc && !this.mainContainer) { - // const doc = CurrentUserUtils.setupMobileDoc(this.userDoc); this.userDoc.activeMobile = this.mainDoc; } } @@ -76,48 +87,22 @@ export default class MobileInterface extends React.Component { }); } - // @action - // switchCurrentView = (view: "main" | "ink" | "upload") => { - // this.currentView = view; - - // if (this.userDoc) { - // switch (view) { - // case "main": { - // // const doc = CurrentUserUtils.setupMobileDoc(this.userDoc); - // this.userDoc.activeMobile = this.mainDoc; - // break; - // } - // case "ink": { - // this.inkDoc = CurrentUserUtils.setupMobileInkingDoc(this.userDoc); - // this.userDoc.activeMobile = this.inkDoc; - // InkingControl.Instance.switchTool(InkTool.Pen); - // this.drawingInk = true; - - // DocServer.Mobile.dispatchOverlayTrigger({ - // enableOverlay: true, - // width: window.innerWidth, - // height: window.innerHeight - // }); - - // break; - // } - // case "upload": { - // this.uploadDoc = CurrentUserUtils.setupMobileUploadDoc(this.userDoc); - // this.userDoc.activeMobile = this.uploadDoc; - - // } - // } - // } - // } + onSwitchUpload = () => { + DocServer.Mobile.dispatchOverlayTrigger({ + enableOverlay: true, + width: 100, + height: 100 + }); + } renderDefaultContent = () => { - console.log("rendering default content"); + console.log("rendering default content", this.mainContainer); if (this.mainContainer) { return { console.log("want to add doc to default content", StrCast(doc.title)); return false; }} addDocTab={returnFalse} pinToPres={emptyFunction} removeDocument={undefined} @@ -192,42 +177,54 @@ export default class MobileInterface extends React.Component {
- - window.innerHeight} - PanelWidth={() => window.innerWidth} - focus={emptyFunction} - isSelected={returnFalse} - select={emptyFunction} - active={returnFalse} - ContentScaling={returnOne} - whenActiveChanged={returnFalse} - ScreenToLocalTransform={Transform.Identity} - ruleProvider={undefined} - renderDepth={0} - ContainingCollectionView={undefined} - ContainingCollectionDoc={undefined}> - - + window.innerHeight} + PanelWidth={() => window.innerWidth} + focus={emptyFunction} + isSelected={returnFalse} + select={emptyFunction} + active={returnFalse} + ContentScaling={returnOne} + whenActiveChanged={returnFalse} + ScreenToLocalTransform={Transform.Identity} + ruleProvider={undefined} + renderDepth={0} + ContainingCollectionView={undefined} + ContainingCollectionDoc={undefined}> +
); } } - upload = () => { + upload = async (e: React.MouseEvent) => { + if (this.mainContainer) { + const data = Cast(this.mainContainer.data, listSpec(Doc)); + if (data) { + const uploadDoc = await data[1]; // TODO: ensure this is the collection to upload + console.log("UPLOADING DOCUMENT FROM MOBILE", uploadDoc[Id], StrCast(uploadDoc.proto!.title)); + if (uploadDoc) { + DocServer.Mobile.dispatchMobileDocumentUpload({ + docId: uploadDoc[Id] + }); + } + } + } + e.stopPropagation(); + e.preventDefault(); } renderUploadContent() { if (this.mainContainer) { return ( -
+
@@ -240,7 +237,7 @@ export default class MobileInterface extends React.Component { Document={this.mainContainer} DataDoc={undefined} LibraryPath={emptyPath} - addDocument={returnFalse} + addDocument={(doc: Doc) => { console.log("want to add doc", StrCast(doc.title)); return false; }} addDocTab={returnFalse} pinToPres={emptyFunction} removeDocument={undefined} @@ -266,13 +263,35 @@ export default class MobileInterface extends React.Component { } } + onDragOver = (e: React.DragEvent) => { + e.preventDefault(); + e.stopPropagation(); + } + render() { // const content = this.currentView === "main" ? this.mainContent : // this.currentView === "ink" ? this.inkContent : // this.currentView === "upload" ? this.uploadContent : <>; return ( -
- {this.renderView ? this.renderView() : this.renderDefaultContent()} +
+ {/* + + {this.renderView ? this.renderView() : this.renderDefaultContent()} + */} + + {/* + + */} + + + {this.renderView ? this.renderView() : this.renderDefaultContent()} + + + {/* */} + + {/* + + */}
); } @@ -281,5 +300,6 @@ export default class MobileInterface extends React.Component { Scripting.addGlobal(function switchMobileView(doc: (userDoc: Doc) => Doc, renderView?: () => JSX.Element, onSwitch?: () => void) { return MobileInterface.Instance.switchCurrentView(doc, renderView, onSwitch); }); Scripting.addGlobal(function onSwitchMobileInking() { return MobileInterface.Instance.onSwitchInking(); }); Scripting.addGlobal(function renderMobileInking() { return MobileInterface.Instance.renderInkingContent(); }); +Scripting.addGlobal(function onSwitchMobileUpload() { return MobileInterface.Instance.onSwitchUpload(); }); Scripting.addGlobal(function renderMobileUpload() { return MobileInterface.Instance.renderUploadContent(); }); diff --git a/src/server/ApiManagers/UploadManager.ts b/src/server/ApiManagers/UploadManager.ts index 74f45ae62..e76d9b7a2 100644 --- a/src/server/ApiManagers/UploadManager.ts +++ b/src/server/ApiManagers/UploadManager.ts @@ -42,6 +42,7 @@ export default class UploadManager extends ApiManager { method: Method.POST, subscription: "/upload", secureHandler: async ({ req, res }) => { + console.log("/upload register"); const form = new formidable.IncomingForm(); form.uploadDir = pathToDirectory(Directory.parsed_files); form.keepExtensions = true; diff --git a/src/server/Message.ts b/src/server/Message.ts index 236df3f3c..c23a2f0a8 100644 --- a/src/server/Message.ts +++ b/src/server/Message.ts @@ -1,5 +1,6 @@ import { Utils } from "../Utils"; import { Point } from "../pen-gestures/ndollar"; +import { Doc } from "../new_fields/Doc"; export class Message { private _name: string; @@ -62,6 +63,10 @@ export interface UpdateMobileInkOverlayPositionContent { readonly dsize?: number; } +export interface MobileDocumentUploadContent { + readonly docId: string; +} + export namespace MessageStore { export const Foo = new Message("Foo"); export const Bar = new Message("Bar"); @@ -75,6 +80,7 @@ export namespace MessageStore { export const GesturePoints = new Message("Gesture Points"); export const MobileInkOverlayTrigger = new Message("Trigger Mobile Ink Overlay"); export const UpdateMobileInkOverlayPosition = new Message("Update Mobile Ink Overlay Position"); + export const MobileDocumentUpload = new Message("Upload Document From Mobile"); export const GetRefField = new Message("Get Ref Field"); export const GetRefFields = new Message("Get Ref Fields"); diff --git a/src/server/Websocket/Websocket.ts b/src/server/Websocket/Websocket.ts index 77816c897..798bdae67 100644 --- a/src/server/Websocket/Websocket.ts +++ b/src/server/Websocket/Websocket.ts @@ -1,5 +1,5 @@ import { Utils } from "../../Utils"; -import { MessageStore, Transferable, Types, Diff, YoutubeQueryInput, YoutubeQueryTypes, GestureContent, MobileInkOverlayContent, UpdateMobileInkOverlayPositionContent } from "../Message"; +import { MessageStore, Transferable, Types, Diff, YoutubeQueryInput, YoutubeQueryTypes, GestureContent, MobileInkOverlayContent, UpdateMobileInkOverlayPositionContent, MobileDocumentUploadContent } from "../Message"; import { Client } from "../Client"; import { Socket } from "socket.io"; import { Database } from "../database"; @@ -57,6 +57,7 @@ export namespace WebSocket { Utils.AddServerHandler(socket, MessageStore.GesturePoints, content => processGesturePoints(socket, content)); Utils.AddServerHandler(socket, MessageStore.MobileInkOverlayTrigger, content => processOverlayTrigger(socket, content)); Utils.AddServerHandler(socket, MessageStore.UpdateMobileInkOverlayPosition, content => processUpdateOverlayPosition(socket, content)); + Utils.AddServerHandler(socket, MessageStore.MobileDocumentUpload, content => processMobileDocumentUpload(socket, content)); Utils.AddServerHandlerCallback(socket, MessageStore.GetRefField, GetRefField); Utils.AddServerHandlerCallback(socket, MessageStore.GetRefFields, GetRefFields); @@ -83,6 +84,10 @@ export namespace WebSocket { socket.broadcast.emit("receiveUpdateOverlayPosition", content); } + function processMobileDocumentUpload(socket: Socket, content: MobileDocumentUploadContent) { + socket.broadcast.emit("receiveMobileDocumentUpload", content); + } + function HandleYoutubeQuery([query, callback]: [YoutubeQueryInput, (result?: any[]) => void]) { const { ProjectCredentials } = GoogleCredentialsLoader; switch (query.type) { diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 817cf40b1..3e5953ac1 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -103,7 +103,7 @@ export class CurrentUserUtils { { title: "use scrubber", icon: "eraser", click: 'activateScrubber(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "green", activePen: doc }, { title: "use drag", icon: "mouse-pointer", click: 'deactivateInk();this.activePen.pen = this;', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "white", activePen: doc }, { title: "draw", icon: "pen-nib", click: 'switchMobileView(setupMobileInkingDoc, renderMobileInking, onSwitchMobileInking);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "red", activePen: doc }, - { title: "upload", icon: "upload", click: 'switchMobileView(setupMobileUploadDoc, renderMobileUpload);', backgroundColor: "orange" }, + { title: "upload", icon: "upload", click: 'switchMobileView(setupMobileUploadDoc, renderMobileUpload, onSwitchMobileUpload);', backgroundColor: "orange" }, { title: "upload", icon: "upload", click: 'uploadImageMobile();', backgroundColor: "cyan" }, ]; return docProtoData.filter(d => !buttons || !buttons.includes(d.title)).map(data => Docs.Create.FontIconDocument({ @@ -138,7 +138,9 @@ export class CurrentUserUtils { } static setupMobileDoc(userDoc: Doc) { - return userDoc.activeMoble ?? Docs.Create.MasonryDocument(CurrentUserUtils.setupMobileButtons(userDoc), { + const webDoc = Docs.Create.WebDocument("https://wikipedia.com", { title: "Mobile Upload Web", chromeStatus: "enabled" }); + + return userDoc.activeMoble ?? Docs.Create.MasonryDocument([webDoc, ...CurrentUserUtils.setupMobileButtons(userDoc)], { columnWidth: 100, ignoreClick: true, lockedPosition: true, chromeStatus: "disabled", title: "buttons", autoHeight: true, yMargin: 5 }); } @@ -148,13 +150,14 @@ export class CurrentUserUtils { } static setupMobileUploadDoc(userDoc: Doc) { - console.log("setup mobile upload", window.innerWidth, window.innerHeight); - const webDoc = Docs.Create.WebDocument("https://wikipedia.com", { title: "Mobile Upload Web", chromeStatus: "enabled" }); - const uploadDoc = Docs.Create.StackingDocument([], { title: "Mobile Upload", backgroundColor: "pink" }); - return Docs.Create.StackingDocument([webDoc, uploadDoc], { - title: "Mobile Upload", backgroundColor: "white", - columnWidth: window.innerWidth, ignoreClick: true, lockedPosition: true, chromeStatus: "disabled", autoHeight: true, yMargin: 5, - width: window.innerWidth, height: window.innerHeight + const webDoc = Docs.Create.WebDocument("https://yahoo.com", { title: "Upload Images From the Web", chromeStatus: "enabled" }); + const uploadDoc = Docs.Create.StackingDocument([], { title: "Mobile Upload Collection", backgroundColor: "pink" }); + console.log("window size", window.innerWidth, window.innerHeight); + // return Docs.Create.StackingDocument([webDoc, uploadDoc], { + // columnWidth: window.innerWidth, //ignoreClick: true, lockedPosition: true, chromeStatus: "disabled", title: "Mobile Upload", autoHeight: true, yMargin: 5 + // }); + return Docs.Create.StackingDocument([webDoc, uploadDoc], {//...CurrentUserUtils.setupMobileButtons(userDoc)], { + columnWidth: 100, lockedPosition: true, chromeStatus: "disabled", title: "Upload", autoHeight: true, yMargin: 30 }); } diff --git a/src/server/server_Initialization.ts b/src/server/server_Initialization.ts index cbe070293..5f1ecc733 100644 --- a/src/server/server_Initialization.ts +++ b/src/server/server_Initialization.ts @@ -42,18 +42,18 @@ export default async function InitializeServer(routeSetter: RouteSetter) { } }; app.use(cors(corsOptions)); - app.use("*", ({ user, originalUrl }, res, next) => { - if (user && !originalUrl.includes("Heartbeat")) { - const userEmail = (user as any).email; - if (userEmail) { - timeMap[userEmail] = Date.now(); - } - } - if (!user && originalUrl === "/") { - return res.redirect("/login"); - } - next(); - }); + // app.use("*", ({ user, originalUrl }, res, next) => { + // if (user && !originalUrl.includes("Heartbeat")) { + // const userEmail = (user as any).email; + // if (userEmail) { + // timeMap[userEmail] = Date.now(); + // } + // } + // if (!user && originalUrl === "/") { + // return res.redirect("/login"); + // } + // next(); + // }); app.use(wdm(compiler, { publicPath: config.output.publicPath })); app.use(whm(compiler)); -- cgit v1.2.3-70-g09d2 From 60a008f635177acccaa9dacb4006491725c93702 Mon Sep 17 00:00:00 2001 From: bob Date: Mon, 10 Feb 2020 15:05:30 -0500 Subject: small cleanups to adding stacking views to contentfittingboxes (like time/pivot). needs to have nativeWidth/Height set. --- src/client/documents/Documents.ts | 4 +++ src/client/util/RichTextRules.ts | 19 ++++++------ src/client/util/RichTextSchema.tsx | 18 +++++------ .../views/collections/CollectionStackingView.tsx | 35 +++++++++------------- src/client/views/collections/CollectionSubView.tsx | 5 +++- .../views/collections/CollectionTimeView.tsx | 3 +- src/client/views/collections/CollectionView.tsx | 6 ++-- .../CollectionFreeFormLayoutEngines.tsx | 2 +- .../collectionFreeForm/CollectionFreeFormView.tsx | 23 +++++++------- .../CollectionMulticolumnView.scss | 2 +- .../CollectionMultirowView.scss | 2 +- src/client/views/nodes/DocumentView.tsx | 20 ++++++++----- src/new_fields/Doc.ts | 17 +++++++++-- .../authentication/models/current_user_utils.ts | 6 ++-- 14 files changed, 87 insertions(+), 75 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 6775d2302..29f253115 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -594,6 +594,10 @@ export namespace Docs { export function MulticolumnDocument(documents: Array, options: DocumentOptions) { return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", schemaColumns: new List([new SchemaHeaderField("title", "#f1efeb")]), ...options, _viewType: CollectionViewType.Multicolumn }); } + export function MultirowDocument(documents: Array, options: DocumentOptions) { + return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", schemaColumns: new List([new SchemaHeaderField("title", "#f1efeb")]), ...options, _viewType: CollectionViewType.Multirow }); + } + export function MasonryDocument(documents: Array, options: DocumentOptions) { return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", schemaColumns: new List([new SchemaHeaderField("title", "#f1efeb")]), ...options, _viewType: CollectionViewType.Masonry }); diff --git a/src/client/util/RichTextRules.ts b/src/client/util/RichTextRules.ts index 3b30b5b3f..1b67b4fe4 100644 --- a/src/client/util/RichTextRules.ts +++ b/src/client/util/RichTextRules.ts @@ -1,17 +1,16 @@ -import { textblockTypeInputRule, smartQuotes, emDash, ellipsis, InputRule } from "prosemirror-inputrules"; -import { schema } from "./RichTextSchema"; -import { wrappingInputRule } from "./prosemirrorPatches"; +import { ellipsis, emDash, InputRule, smartQuotes, textblockTypeInputRule } from "prosemirror-inputrules"; import { NodeSelection, TextSelection } from "prosemirror-state"; -import { StrCast, Cast, NumCast } from "../../new_fields/Types"; -import { Doc, DataSym } from "../../new_fields/Doc"; -import { FormattedTextBox } from "../views/nodes/FormattedTextBox"; -import { Docs, DocUtils } from "../documents/Documents"; +import { DataSym, Doc } from "../../new_fields/Doc"; import { Id } from "../../new_fields/FieldSymbols"; -import { DocServer } from "../DocServer"; +import { ComputedField } from "../../new_fields/ScriptField"; +import { Cast, NumCast } from "../../new_fields/Types"; import { returnFalse, Utils } from "../../Utils"; +import { DocServer } from "../DocServer"; +import { Docs, DocUtils } from "../documents/Documents"; +import { FormattedTextBox } from "../views/nodes/FormattedTextBox"; +import { wrappingInputRule } from "./prosemirrorPatches"; import RichTextMenu from "./RichTextMenu"; -import { RichTextField } from "../../new_fields/RichTextField"; -import { ComputedField } from "../../new_fields/ScriptField"; +import { schema } from "./RichTextSchema"; export const inpRules = { rules: [ diff --git a/src/client/util/RichTextSchema.tsx b/src/client/util/RichTextSchema.tsx index c07ebe2ed..043b277de 100644 --- a/src/client/util/RichTextSchema.tsx +++ b/src/client/util/RichTextSchema.tsx @@ -1,28 +1,26 @@ -import { reaction, IReactionDisposer, observable, runInAction } from "mobx"; +import { IReactionDisposer, observable, reaction, runInAction } from "mobx"; import { baseKeymap, toggleMark } from "prosemirror-commands"; import { redo, undo } from "prosemirror-history"; import { keymap } from "prosemirror-keymap"; import { DOMOutputSpecArray, Fragment, MarkSpec, Node, NodeSpec, Schema, Slice } from "prosemirror-model"; import { bulletList, listItem, orderedList } from 'prosemirror-schema-list'; -import { EditorState, NodeSelection, TextSelection, Plugin } from "prosemirror-state"; +import { EditorState, NodeSelection, Plugin, TextSelection } from "prosemirror-state"; import { StepMap } from "prosemirror-transform"; import { EditorView } from "prosemirror-view"; import * as ReactDOM from 'react-dom'; -import { Doc, WidthSym, HeightSym, DataSym, Field } from "../../new_fields/Doc"; +import { Doc, Field, HeightSym, WidthSym } from "../../new_fields/Doc"; +import { Id } from "../../new_fields/FieldSymbols"; +import { ObjectField } from "../../new_fields/ObjectField"; +import { ComputedField } from "../../new_fields/ScriptField"; +import { BoolCast, NumCast, StrCast } from "../../new_fields/Types"; import { emptyFunction, returnEmptyString, returnFalse, returnOne, Utils } from "../../Utils"; import { DocServer } from "../DocServer"; import { DocumentView } from "../views/nodes/DocumentView"; +import { FormattedTextBox } from "../views/nodes/FormattedTextBox"; import { DocumentManager } from "./DocumentManager"; import ParagraphNodeSpec from "./ParagraphNodeSpec"; import { Transform } from "./Transform"; import React = require("react"); -import { BoolCast, NumCast, StrCast } from "../../new_fields/Types"; -import { FormattedTextBox } from "../views/nodes/FormattedTextBox"; -import { ObjectField } from "../../new_fields/ObjectField"; -import { ComputedField } from "../../new_fields/ScriptField"; -import { observer } from "mobx-react"; -import { Id } from "../../new_fields/FieldSymbols"; -import { OnChangeHandler } from "react-color/lib/components/common/ColorWrap"; const blockquoteDOM: DOMOutputSpecArray = ["blockquote", 0], hrDOM: DOMOutputSpecArray = ["hr"], preDOM: DOMOutputSpecArray = ["pre", ["code", 0]], brDOM: DOMOutputSpecArray = ["br"], ulDOM: DOMOutputSpecArray = ["ul", 0]; diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index d772ace23..21c34d047 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -4,25 +4,25 @@ import { CursorProperty } from "csstype"; import { action, computed, IReactionDisposer, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; import Switch from 'rc-switch'; -import { Doc, HeightSym, WidthSym, DataSym } from "../../../new_fields/Doc"; +import { Doc, HeightSym, WidthSym } from "../../../new_fields/Doc"; import { Id } from "../../../new_fields/FieldSymbols"; import { List } from "../../../new_fields/List"; import { listSpec } from "../../../new_fields/Schema"; import { SchemaHeaderField } from "../../../new_fields/SchemaHeaderField"; -import { BoolCast, Cast, NumCast, StrCast, ScriptCast } from "../../../new_fields/Types"; -import { emptyFunction, Utils } from "../../../Utils"; +import { BoolCast, Cast, NumCast, ScriptCast, StrCast } from "../../../new_fields/Types"; +import { TraceMobx } from "../../../new_fields/util"; +import { Utils } from "../../../Utils"; import { DragManager } from "../../util/DragManager"; import { Transform } from "../../util/Transform"; import { undoBatch } from "../../util/UndoManager"; +import { ContextMenu } from "../ContextMenu"; +import { ContextMenuProps } from "../ContextMenuItem"; import { EditableView } from "../EditableView"; import { ContentFittingDocumentView } from "../nodes/ContentFittingDocumentView"; +import { CollectionMasonryViewFieldRow } from "./CollectionMasonryViewFieldRow"; import "./CollectionStackingView.scss"; import { CollectionStackingViewFieldColumn } from "./CollectionStackingViewFieldColumn"; import { CollectionSubView } from "./CollectionSubView"; -import { ContextMenu } from "../ContextMenu"; -import { ContextMenuProps } from "../ContextMenuItem"; -import { CollectionMasonryViewFieldRow } from "./CollectionMasonryViewFieldRow"; -import { TraceMobx } from "../../../new_fields/util"; import { CollectionViewType } from "./CollectionView"; @observer @@ -55,7 +55,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { this._docXfs.length = 0; return docs.map((d, i) => { const height = () => this.getDocHeight(d); - const width = () => this.widthScale * Math.min(d._nativeWidth && !d.ignoreAspect && !this.props.Document.fillColumn ? d[WidthSym]() : Number.MAX_VALUE, this.columnWidth / this.numGroupColumns); + const width = () => Math.min(d._nativeWidth && !d.ignoreAspect && !this.props.Document.fillColumn ? d[WidthSym]() : Number.MAX_VALUE, this.columnWidth / this.numGroupColumns); const dref = React.createRef(); const dxf = () => this.getDocTransform(d, dref.current!); this._docXfs.push({ dxf: dxf, width: width, height: height }); @@ -376,16 +376,9 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { } return sections.map(section => this.isStackingView ? this.sectionStacking(section[0], section[1]) : this.sectionMasonry(section[0], section[1])); } - @computed get contentScale() { - const heightExtra = this.heightPercent > 1 ? this.heightPercent : 1; - return Math.min(this.props.Document[WidthSym]() / this.props.PanelWidth(), heightExtra * this.props.Document[HeightSym]() / this.props.PanelHeight()); - } - @computed get widthScale() { - return this.heightPercent < 1 ? Math.max(1, this.contentScale) : 1; - } - @computed get heightPercent() { - return this.props.PanelHeight() / this.layoutDoc[HeightSym](); - } + + @computed get scaling() { return !this.props.Document._nativeWidth ? 1 : this.props.PanelHeight() / NumCast(this.props.Document._nativeHeight); } + render() { TraceMobx(); const editableViewProps = { @@ -399,9 +392,9 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { ref={this.createRef} style={{ overflowY: this.props.active() ? "auto" : "hidden", - transform: `scale(${Math.min(1, this.heightPercent)})`, - height: `${100 * Math.max(1, this.contentScale)}%`, - width: `${100 * this.widthScale}%`, + transform: `scale(${this.scaling}`, + height: `${1 / this.scaling * 100}%`, + width: `${1 / this.scaling * 100}%`, transformOrigin: "top left", }} onScroll={action((e: React.UIEvent) => this._scroll = e.currentTarget.scrollTop)} diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index 62b9e8380..d71bad647 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -1,7 +1,7 @@ import { action, computed, IReactionDisposer, reaction, trace } from "mobx"; import * as rp from 'request-promise'; import CursorField from "../../../new_fields/CursorField"; -import { Doc, DocListCast, Opt } from "../../../new_fields/Doc"; +import { Doc, DocListCast, Opt, WidthSym, HeightSym } from "../../../new_fields/Doc"; import { Id } from "../../../new_fields/FieldSymbols"; import { List } from "../../../new_fields/List"; import { listSpec } from "../../../new_fields/Schema"; @@ -167,6 +167,9 @@ export function CollectionSubView(schemaCtor: (doc: Doc) => T) { return true; } let added = false; + if (this.props.Document._freezeOnDrop) { + de.complete.docDragData?.droppedDocuments.forEach(drop => Doc.freezeNativeDimensions(drop, drop[WidthSym](), drop[HeightSym]())); + } if (docDragData.dropAction || docDragData.userDropAction) { added = docDragData.droppedDocuments.reduce((added: boolean, d) => this.props.addDocument(d) || added, false); } else if (docDragData.moveDocument) { diff --git a/src/client/views/collections/CollectionTimeView.tsx b/src/client/views/collections/CollectionTimeView.tsx index 6058f4e1d..db176d0bc 100644 --- a/src/client/views/collections/CollectionTimeView.tsx +++ b/src/client/views/collections/CollectionTimeView.tsx @@ -2,7 +2,7 @@ import { faEdit } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { action, computed, observable, runInAction, trace } from "mobx"; import { observer } from "mobx-react"; -import { Doc, DocListCast, Field } from "../../../new_fields/Doc"; +import { Doc, DocListCast, Field, WidthSym, HeightSym } from "../../../new_fields/Doc"; import { List } from "../../../new_fields/List"; import { ObjectField } from "../../../new_fields/ObjectField"; import { RichTextField } from "../../../new_fields/RichTextField"; @@ -31,6 +31,7 @@ export class CollectionTimeView extends CollectionSubView(doc => doc) { @observable _layoutEngine = "pivot"; componentDidMount() { + this.props.Document._freezeOnDrop = true; const childDetailed = this.props.Document.childDetailed; // bcz: needs to be here to make sure the childDetailed layout template has been loaded when the first item is clicked; if (!this.props.Document._facetCollection) { const facetCollection = Docs.Create.TreeDocument([], { title: "facetFilters", _yMargin: 0, treeViewHideTitle: true, treeViewHideHeaderFields: true }); diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index 2f27e5273..c081649cc 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -7,7 +7,7 @@ import * as React from 'react'; import Lightbox from 'react-image-lightbox-with-rotate'; import 'react-image-lightbox-with-rotate/style.css'; // This only needs to be imported once in your app import { DateField } from '../../../new_fields/DateField'; -import { Doc, DocListCast } from '../../../new_fields/Doc'; +import { Doc, DocListCast, DataSym } from '../../../new_fields/Doc'; import { Id } from '../../../new_fields/FieldSymbols'; import { listSpec } from '../../../new_fields/Schema'; import { BoolCast, Cast, StrCast, NumCast } from '../../../new_fields/Types'; @@ -133,7 +133,7 @@ export class CollectionView extends Touchable { @action.bound addDocument(doc: Doc): boolean { - const targetDataDoc = Doc.GetProto(this.props.DataDoc || this.props.Document); // bcz: shouldn't this be Doc.Layout(this.props.Document)? Right now, that causes problems with Buxton layout & adding things to a SLideView + const targetDataDoc = this.props.Document[DataSym]; Doc.AddDocToList(targetDataDoc, this.props.fieldKey, doc); targetDataDoc[this.props.fieldKey + "-lastModified"] = new DateField(new Date(Date.now())); Doc.GetProto(doc).lastOpened = new DateField; @@ -144,7 +144,7 @@ export class CollectionView extends Touchable { removeDocument(doc: Doc): boolean { const docView = DocumentManager.Instance.getDocumentView(doc, this.props.ContainingCollectionView); docView && SelectionManager.DeselectDoc(docView); - const value = Cast(Doc.GetProto(this.props.DataDoc || this.props.Document)[this.props.fieldKey], listSpec(Doc), []); + const value = Cast(this.props.Document[DataSym][this.props.fieldKey], listSpec(Doc), []); let index = value.reduce((p, v, i) => (v instanceof Doc && v === doc) ? i : p, -1); index = index !== -1 ? index : value.reduce((p, v, i) => (v instanceof Doc && Doc.AreProtosEqual(v, doc)) ? i : p, -1); diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx index baf09fe5b..da4dc0270 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx @@ -186,7 +186,7 @@ export function computePivotLayout( const maxColHeight = pivotAxisWidth * expander * Math.ceil(maxInColumn / numCols); const dividers = sortedPivotKeys.map((key, i) => - ({ type: "div", color: "lightGray", x: i * pivotAxisWidth * (numCols * expander + gap), y: -maxColHeight + pivotAxisWidth, width: pivotAxisWidth * numCols * expander, height: maxColHeight, payload: pivotColumnGroups.get(key)!.filters })); + ({ type: "div", color: "lightGray", x: i * pivotAxisWidth * (numCols * expander + gap) - pivotAxisWidth * (expander - 1) / 2, y: -maxColHeight + pivotAxisWidth, width: pivotAxisWidth * numCols * expander, height: maxColHeight, payload: pivotColumnGroups.get(key)!.filters })); groupNames.push(...dividers); return normalizeResults(panelDim, max_text, childPairs, docMap, poolData, viewDefsToJSX, groupNames, 0, [], childDocs.filter(c => !filterDocs.includes(c))); } diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index c78a2a2cf..07a5a2c7b 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -1,20 +1,22 @@ import { library } from "@fortawesome/fontawesome-svg-core"; import { faEye } from "@fortawesome/free-regular-svg-icons"; import { faBraille, faChalkboard, faCompass, faCompressArrowsAlt, faExpandArrowsAlt, faFileUpload, faPaintBrush, faTable, faUpload } from "@fortawesome/free-solid-svg-icons"; -import { action, computed, observable, ObservableMap, reaction, runInAction, IReactionDisposer, trace } from "mobx"; +import { action, computed, IReactionDisposer, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; -import { Doc, DocListCast, HeightSym, Opt, WidthSym, DocListCastAsync, Field } from "../../../../new_fields/Doc"; +import { computedFn } from "mobx-utils"; +import { Doc, DocListCast, HeightSym, Opt, WidthSym } from "../../../../new_fields/Doc"; import { documentSchema, positionSchema } from "../../../../new_fields/documentSchemas"; import { Id } from "../../../../new_fields/FieldSymbols"; -import { InkTool, InkField, InkData } from "../../../../new_fields/InkField"; -import { createSchema, makeInterface, listSpec } from "../../../../new_fields/Schema"; +import { InkTool } from "../../../../new_fields/InkField"; +import { createSchema, listSpec, makeInterface } from "../../../../new_fields/Schema"; import { ScriptField } from "../../../../new_fields/ScriptField"; -import { BoolCast, Cast, DateCast, NumCast, StrCast, ScriptCast } from "../../../../new_fields/Types"; +import { Cast, NumCast, ScriptCast, StrCast } from "../../../../new_fields/Types"; +import { TraceMobx } from "../../../../new_fields/util"; +import { GestureUtils } from "../../../../pen-gestures/GestureUtils"; import { CurrentUserUtils } from "../../../../server/authentication/models/current_user_utils"; -import { aggregateBounds, emptyFunction, intersectRect, returnOne, Utils } from "../../../../Utils"; +import { aggregateBounds, intersectRect, returnOne, Utils } from "../../../../Utils"; import { DocServer } from "../../../DocServer"; -import { Docs, DocUtils } from "../../../documents/Documents"; -import { DocumentType } from "../../../documents/DocumentTypes"; +import { Docs } from "../../../documents/Documents"; import { DocumentManager } from "../../../util/DocumentManager"; import { DragManager } from "../../../util/DragManager"; import { HistoryUtil } from "../../../util/History"; @@ -32,15 +34,12 @@ import { FormattedTextBox } from "../../nodes/FormattedTextBox"; import { pageSchema } from "../../nodes/ImageBox"; import PDFMenu from "../../pdf/PDFMenu"; import { CollectionSubView } from "../CollectionSubView"; -import { computePivotLayout, ViewDefResult, computeTimelineLayout, PoolData, ViewDefBounds } from "./CollectionFreeFormLayoutEngines"; +import { computePivotLayout, computeTimelineLayout, PoolData, ViewDefBounds, ViewDefResult } from "./CollectionFreeFormLayoutEngines"; import { CollectionFreeFormRemoteCursors } from "./CollectionFreeFormRemoteCursors"; import "./CollectionFreeFormView.scss"; import MarqueeOptionsMenu from "./MarqueeOptionsMenu"; import { MarqueeView } from "./MarqueeView"; import React = require("react"); -import { computedFn } from "mobx-utils"; -import { TraceMobx } from "../../../../new_fields/util"; -import { GestureUtils } from "../../../../pen-gestures/GestureUtils"; library.add(faEye as any, faTable, faPaintBrush, faExpandArrowsAlt, faCompressArrowsAlt, faCompass, faUpload, faBraille, faChalkboard, faFileUpload); diff --git a/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.scss b/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.scss index 0c74b8ddb..821c8d804 100644 --- a/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.scss +++ b/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.scss @@ -1,8 +1,8 @@ .collectionMulticolumnView_contents { display: flex; + overflow: hidden; width: 100%; height: 100%; - overflow: hidden; .document-wrapper { display: flex; diff --git a/src/client/views/collections/collectionMulticolumn/CollectionMultirowView.scss b/src/client/views/collections/collectionMulticolumn/CollectionMultirowView.scss index 64f607680..a7e2c5707 100644 --- a/src/client/views/collections/collectionMulticolumn/CollectionMultirowView.scss +++ b/src/client/views/collections/collectionMulticolumn/CollectionMultirowView.scss @@ -1,8 +1,8 @@ .collectionMultirowView_contents { display: flex; + overflow: hidden; width: 100%; height: 100%; - overflow: hidden; flex-direction: column; .document-wrapper { diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 1199ed7ee..080b01df2 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -610,13 +610,17 @@ export class DocumentView extends DocComponent(Docu } @undoBatch - @action - freezeNativeDimensions = (): void => { - this.layoutDoc._autoHeight = false; - this.layoutDoc.ignoreAspect = !this.layoutDoc.ignoreAspect; - if (!this.layoutDoc.ignoreAspect && !this.layoutDoc._nativeWidth) { - this.layoutDoc._nativeWidth = this.props.PanelWidth(); - this.layoutDoc._nativeHeight = this.props.PanelHeight(); + public static unfreezeNativeDimensions = action((layoutDoc: Doc): void => { + layoutDoc._nativeWidth = undefined; + layoutDoc._nativeHeight = undefined; + }); + + toggleNativeDimensions = () => { + if (this.Document._nativeWidth || this.Document._nativeHeight) { + DocumentView.unfreezeNativeDimensions(this.layoutDoc); + } + else { + Doc.freezeNativeDimensions(this.layoutDoc, this.props.PanelWidth(), this.props.PanelHeight()); } } @@ -730,7 +734,7 @@ export class DocumentView extends DocComponent(Docu layoutItems.push({ description: `${this.Document._chromeStatus !== "disabled" ? "Hide" : "Show"} Chrome`, event: () => this.Document._chromeStatus = (this.Document._chromeStatus !== "disabled" ? "disabled" : "enabled"), icon: "project-diagram" }); layoutItems.push({ description: `${this.Document._autoHeight ? "Variable Height" : "Auto Height"}`, event: () => this.layoutDoc._autoHeight = !this.layoutDoc._autoHeight, icon: "plus" }); - layoutItems.push({ description: this.Document.ignoreAspect || !this.Document._nativeWidth || !this.Document._nativeHeight ? "Freeze" : "Unfreeze", event: this.freezeNativeDimensions, icon: "snowflake" }); + layoutItems.push({ description: !this.Document._nativeWidth || !this.Document._nativeHeight ? "Freeze" : "Unfreeze", event: this.toggleNativeDimensions, icon: "snowflake" }); layoutItems.push({ description: this.Document.lockedPosition ? "Unlock Position" : "Lock Position", event: this.toggleLockPosition, icon: BoolCast(this.Document.lockedPosition) ? "unlock" : "lock" }); layoutItems.push({ description: this.Document.lockedTransform ? "Unlock Transform" : "Lock Transform", event: this.toggleLockTransform, icon: BoolCast(this.Document.lockedTransform) ? "unlock" : "lock" }); layoutItems.push({ description: "Center View", event: () => this.props.focus(this.props.Document, false), icon: "crosshairs" }); diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index 3baab119f..a28c6f58f 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -14,7 +14,7 @@ import { ComputedField, ScriptField } from "./ScriptField"; import { BoolCast, Cast, FieldValue, NumCast, StrCast, ToConstructor } from "./Types"; import { deleteProperty, getField, getter, makeEditable, makeReadOnly, setter, updateFunction } from "./util"; import { intersectRect } from "../Utils"; -import { UndoManager } from "../client/util/UndoManager"; +import { UndoManager, undoBatch } from "../client/util/UndoManager"; import { computedFn } from "mobx-utils"; import { RichTextField } from "./RichTextField"; import { Script } from "vm"; @@ -178,7 +178,7 @@ export class Doc extends RefField { private [SelfProxy]: any; public [WidthSym] = () => NumCast(this[SelfProxy]._width); public [HeightSym] = () => NumCast(this[SelfProxy]._height); - public get [DataSym]() { return Cast(this[SelfProxy].resolvedDataDoc, Doc, null) || this[SelfProxy]; } + public get [DataSym]() { return Cast(Doc.Layout(this[SelfProxy]).resolvedDataDoc, Doc, null) || this[SelfProxy]; } public get [LayoutSym]() { return this[SelfProxy].__LAYOUT__; } @computed get __LAYOUT__() { const templateLayoutDoc = Cast(Doc.LayoutField(this[SelfProxy]), Doc, null); @@ -842,6 +842,17 @@ export namespace Doc { } } } + + @undoBatch + @action + export function freezeNativeDimensions(layoutDoc: Doc, width: number, height: number): void { + layoutDoc._autoHeight = false; + layoutDoc.ignoreAspect = false; + if (!layoutDoc.ignoreAspect && !layoutDoc._nativeWidth) { + layoutDoc._nativeWidth = NumCast(layoutDoc._width, width); + layoutDoc._nativeHeight = NumCast(layoutDoc._height, height); + } + } } Scripting.addGlobal(function renameAlias(doc: any, n: any) { return StrCast(Doc.GetProto(doc).title).replace(/\([0-9]*\)/, "") + `(${n})`; }); @@ -867,4 +878,4 @@ Scripting.addGlobal(function selectedDocs(container: Doc, excludeCollections: bo return docs.length ? new List(docs) : prevValue; }); Scripting.addGlobal(function setDocFilter(container: Doc, key: string, value: any, modifiers?: string) { Doc.setDocFilter(container, key, value, modifiers); }); -Scripting.addGlobal(function setDocFilterRange(container: Doc, key: string, range: number) { Doc.setDocFilterRange(container, key, range); }); \ No newline at end of file +Scripting.addGlobal(function setDocFilterRange(container: Doc, key: string, range: number[]) { Doc.setDocFilterRange(container, key, range); }); \ No newline at end of file diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index efee42f63..ea7a4999c 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -234,12 +234,12 @@ export class CurrentUserUtils { /// sets up the default list of buttons to be shown in the expanding button menu at the bottom of the Dash window static setupExpandingButtons(doc: Doc) { - const slideTemplate = Docs.Create.StackingDocument( + const slideTemplate = Docs.Create.MultirowDocument( [ - Docs.Create.MulticolumnDocument([], { title: "images", _height: 200, _xMargin: 10, _yMargin: 10 }), + Docs.Create.MulticolumnDocument([], { title: "images", _height: 200 }), Docs.Create.TextDocument("", { title: "contents", _height: 100 }) ], - { _width: 400, _height: 300, title: "slide", _chromeStatus: "disabled", backgroundColor: "lightGray", _autoHeight: true }); + { _width: 400, _height: 300, title: "slideView", _chromeStatus: "disabled", _xMargin: 3, _yMargin: 3, backgroundColor: "lightGray", _autoHeight: true }); slideTemplate.isTemplateDoc = makeTemplate(slideTemplate); const iconDoc = Docs.Create.TextDocument("", { title: "icon", _width: 150, _height: 30, isTemplateDoc: true, onClick: ScriptField.MakeScript("setNativeView(this)") }); -- cgit v1.2.3-70-g09d2 From 51a82fddf79e0c838ed2e506d295edb7d9a9bd7b Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Tue, 11 Feb 2020 01:00:51 -0500 Subject: fixes to presentation display box, and timeline min/max/span requests. --- package-lock.json | 49 +++------ .../views/collections/CollectionTimeView.tsx | 4 +- src/client/views/collections/CollectionView.tsx | 3 +- .../CollectionFreeFormLayoutEngines.tsx | 10 +- src/client/views/nodes/DocumentView.scss | 1 - src/client/views/nodes/DocumentView.tsx | 2 +- src/client/views/nodes/PresBox.scss | 8 +- src/client/views/nodes/PresBox.tsx | 111 +++++++++------------ .../authentication/models/current_user_utils.ts | 4 +- 9 files changed, 80 insertions(+), 112 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/package-lock.json b/package-lock.json index c487b11c8..a09df33da 100644 --- a/package-lock.json +++ b/package-lock.json @@ -657,7 +657,7 @@ }, "@types/passport": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@types/passport/-/passport-1.0.2.tgz", + "resolved": "https://registry.npmjs.org/@types/passport/-/passport-1.0.0.tgz", "integrity": "sha512-Pf39AYKf8q+YoONym3150cEwfUD66dtwHJWvbeOzKxnA0GZZ/vAXhNWv9vMhKyRQBQZiQyWQnhYBEBlKW6G8wg==", "requires": { "@types/express": "*" @@ -5406,8 +5406,7 @@ }, "ansi-regex": { "version": "2.1.1", - "bundled": true, - "optional": true + "bundled": true }, "aproba": { "version": "1.2.0", @@ -5425,13 +5424,11 @@ }, "balanced-match": { "version": "1.0.0", - "bundled": true, - "optional": true + "bundled": true }, "brace-expansion": { "version": "1.1.11", "bundled": true, - "optional": true, "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -5444,18 +5441,15 @@ }, "code-point-at": { "version": "1.1.0", - "bundled": true, - "optional": true + "bundled": true }, "concat-map": { "version": "0.0.1", - "bundled": true, - "optional": true + "bundled": true }, "console-control-strings": { "version": "1.1.0", - "bundled": true, - "optional": true + "bundled": true }, "core-util-is": { "version": "1.0.2", @@ -5558,8 +5552,7 @@ }, "inherits": { "version": "2.0.4", - "bundled": true, - "optional": true + "bundled": true }, "ini": { "version": "1.3.5", @@ -5569,7 +5562,6 @@ "is-fullwidth-code-point": { "version": "1.0.0", "bundled": true, - "optional": true, "requires": { "number-is-nan": "^1.0.0" } @@ -5582,20 +5574,17 @@ "minimatch": { "version": "3.0.4", "bundled": true, - "optional": true, "requires": { "brace-expansion": "^1.1.7" } }, "minimist": { "version": "0.0.8", - "bundled": true, - "optional": true + "bundled": true }, "minipass": { "version": "2.9.0", "bundled": true, - "optional": true, "requires": { "safe-buffer": "^5.1.2", "yallist": "^3.0.0" @@ -5612,7 +5601,6 @@ "mkdirp": { "version": "0.5.1", "bundled": true, - "optional": true, "requires": { "minimist": "0.0.8" } @@ -5693,8 +5681,7 @@ }, "number-is-nan": { "version": "1.0.1", - "bundled": true, - "optional": true + "bundled": true }, "object-assign": { "version": "4.1.1", @@ -5704,7 +5691,6 @@ "once": { "version": "1.4.0", "bundled": true, - "optional": true, "requires": { "wrappy": "1" } @@ -5780,8 +5766,7 @@ }, "safe-buffer": { "version": "5.1.2", - "bundled": true, - "optional": true + "bundled": true }, "safer-buffer": { "version": "2.1.2", @@ -5811,7 +5796,6 @@ "string-width": { "version": "1.0.2", "bundled": true, - "optional": true, "requires": { "code-point-at": "^1.0.0", "is-fullwidth-code-point": "^1.0.0", @@ -5829,7 +5813,6 @@ "strip-ansi": { "version": "3.0.1", "bundled": true, - "optional": true, "requires": { "ansi-regex": "^2.0.0" } @@ -5868,13 +5851,11 @@ }, "wrappy": { "version": "1.0.2", - "bundled": true, - "optional": true + "bundled": true }, "yallist": { "version": "3.1.1", - "bundled": true, - "optional": true + "bundled": true } } }, @@ -13925,7 +13906,7 @@ }, "readable-stream": { "version": "2.3.6", - "resolved": "http://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", "requires": { "core-util-is": "~1.0.0", @@ -15529,7 +15510,7 @@ }, "strip-ansi": { "version": "3.0.1", - "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", "requires": { "ansi-regex": "^2.0.0" @@ -17770,7 +17751,7 @@ }, "wrap-ansi": { "version": "2.1.0", - "resolved": "http://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=", "requires": { "string-width": "^1.0.1", diff --git a/src/client/views/collections/CollectionTimeView.tsx b/src/client/views/collections/CollectionTimeView.tsx index db176d0bc..de7fa5ed2 100644 --- a/src/client/views/collections/CollectionTimeView.tsx +++ b/src/client/views/collections/CollectionTimeView.tsx @@ -190,6 +190,7 @@ export class CollectionTimeView extends CollectionSubView(doc => doc) { const minReq = NumCast(this.props.Document[this.props.fieldKey + "-timelineMinReq"], NumCast(this.props.Document[this.props.fieldKey + "-timelineMin"], 0)); const maxReq = NumCast(this.props.Document[this.props.fieldKey + "-timelineMaxReq"], NumCast(this.props.Document[this.props.fieldKey + "-timelineMax"], 10)); this.props.Document[this.props.fieldKey + "-timelineMinReq"] = minReq + (maxReq - minReq) * delta / this.props.PanelWidth(); + this.props.Document[this.props.fieldKey + "-timelineSpan"] = undefined; } onMinUp = (e: PointerEvent) => { document.removeEventListener("pointermove", this.onMinMove); @@ -212,6 +213,7 @@ export class CollectionTimeView extends CollectionSubView(doc => doc) { const minReq = NumCast(this.props.Document[this.props.fieldKey + "-timelineMinReq"], NumCast(this.props.Document[this.props.fieldKey + "-timelineMin"], 0)); const maxReq = NumCast(this.props.Document[this.props.fieldKey + "-timelineMaxReq"], NumCast(this.props.Document[this.props.fieldKey + "-timelineMax"], 10)); this.props.Document[this.props.fieldKey + "-timelineMaxReq"] = maxReq + (maxReq - minReq) * delta / this.props.PanelWidth(); + this.props.Document[this.props.fieldKey + "-timelineSpan"] = undefined; } onMaxUp = (e: PointerEvent) => { document.removeEventListener("pointermove", this.onMaxMove); @@ -331,7 +333,7 @@ export class CollectionTimeView extends CollectionSubView(doc => doc) {
- - + const mode = NumCast(this.props.Document._viewType, CollectionViewType.Invalid); + this.initializeScaleViews(this.childDocs, mode); + return
+
+ + + + +
+
+ {mode !== CollectionViewType.Invalid ? + + : (null) + }
- :
-
- - - - - {this.props.Document.inOverlay ? (null) : -
- -
} -
); +
; } } \ No newline at end of file diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index ea7a4999c..3a2a0f513 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -48,7 +48,7 @@ export class CurrentUserUtils { // setup the "creator" buttons for the sidebar-- eg. the default set of draggable document creation tools static setupCreatorButtons(doc: Doc, buttons?: string[]) { const notes = CurrentUserUtils.setupNoteTypes(doc); - const emptyPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, showTitle: "title", boxShadow: "0 0" }); + const emptyPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, _chromeStatus: "enabled", showTitle: "title", boxShadow: "0 0" }); const emptyCollection = Docs.Create.FreeformDocument([], { _nativeWidth: undefined, _nativeHeight: undefined, _LODdisable: true, _width: 150, _height: 100, title: "freeform" }); doc.noteTypes = Docs.Create.TreeDocument(notes, { title: "Note Types", _height: 75 }); doc.activePen = doc; @@ -270,7 +270,7 @@ export class CurrentUserUtils { // the initial presentation Doc to use static setupDefaultPresentation(doc: Doc) { - doc.curPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, showTitle: "title", boxShadow: "0 0" }); + doc.curPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, _chromeStatus: "enabled", showTitle: "title", boxShadow: "0 0" }); } static setupMobileUploads(doc: Doc) { -- cgit v1.2.3-70-g09d2 From 74ca8ac01e32faa8adab54ddfd806fe46cda03ec Mon Sep 17 00:00:00 2001 From: Hannah Date: Tue, 11 Feb 2020 06:22:04 -0500 Subject: refined upload interaction --- src/client/util/DragManager.ts | 21 ++-- src/client/views/nodes/WebBox.scss | 15 +++ src/client/views/nodes/WebBox.tsx | 130 ++++++++++----------- src/mobile/ImageUpload.tsx | 2 - src/mobile/MobileInkOverlay.scss | 4 +- src/mobile/MobileInkOverlay.tsx | 35 +++--- src/mobile/MobileInterface.scss | 7 +- src/mobile/MobileInterface.tsx | 42 ++++--- src/server/Message.ts | 2 +- .../authentication/models/current_user_utils.ts | 25 ++-- 10 files changed, 146 insertions(+), 137 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index 745540ff9..702c10910 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -195,7 +195,7 @@ export namespace DragManager { dragData.userDropAction === "alias" || (!dragData.userDropAction && dragData.dropAction === "alias") ? Doc.MakeAlias(d) : dragData.userDropAction === "copy" || (!dragData.userDropAction && dragData.dropAction === "copy") ? Doc.MakeCopy(d, true) : d) ); - e.docDragData?.droppedDocuments.forEach((drop: Doc, i: number) => + e.docDragData ?.droppedDocuments.forEach((drop: Doc, i: number) => Cast(dragData.draggedDocuments[i].removeDropProperties, listSpec("string"), []).map(prop => drop[prop] = undefined)); }; dragData.draggedDocuments.map(d => d.dragFactory); // does this help? trying to make sure the dragFactory Doc is loaded @@ -288,6 +288,7 @@ export namespace DragManager { if (!ele.parentNode) dragDiv.appendChild(ele); const dragElement = ele.parentNode === dragDiv ? ele : ele.cloneNode(true) as HTMLElement; const rect = ele.getBoundingClientRect(); + console.log("boudning", rect); const scaleX = rect.width / ele.offsetWidth, scaleY = rect.height / ele.offsetHeight; xs.push(rect.left); @@ -305,7 +306,7 @@ export namespace DragManager { dragElement.style.transformOrigin = "0 0"; dragElement.style.borderRadius = getComputedStyle(ele).borderRadius; dragElement.style.zIndex = globalCssVariables.contextMenuZindex;// "1000"; - dragElement.style.transform = `translate(${rect.left + (options?.offsetX || 0)}px, ${rect.top + (options?.offsetY || 0)}px) scale(${scaleX}, ${scaleY})`; + dragElement.style.transform = `translate(${rect.left + (options ?.offsetX || 0)}px, ${rect.top + (options ?.offsetY || 0)}px) scale(${scaleX}, ${scaleY})`; dragElement.style.width = `${rect.width / scaleX}px`; dragElement.style.height = `${rect.height / scaleY}px`; @@ -334,8 +335,8 @@ export namespace DragManager { return dragElement; }); - const hideSource = options?.hideSource ? true : false; - eles.map(ele => ele.parentElement && ele.parentElement?.className === dragData.dragDivName ? (ele.parentElement.hidden = hideSource) : (ele.hidden = hideSource)); + const hideSource = options ?.hideSource ? true : false; + eles.map(ele => ele.parentElement && ele.parentElement ?.className === dragData.dragDivName ? (ele.parentElement.hidden = hideSource) : (ele.hidden = hideSource)); let lastX = downX; let lastY = downY; @@ -346,7 +347,7 @@ export namespace DragManager { } if (e.shiftKey && CollectionDockingView.Instance) { AbortDrag(); - finishDrag?.(new DragCompleteEvent(true, dragData)); + finishDrag ?.(new DragCompleteEvent(true, dragData)); CollectionDockingView.Instance.StartOtherDrag({ pageX: e.pageX, pageY: e.pageY, @@ -360,13 +361,13 @@ export namespace DragManager { lastX = e.pageX; lastY = e.pageY; dragElements.map((dragElement, i) => (dragElement.style.transform = - `translate(${(xs[i] += moveX) + (options?.offsetX || 0)}px, ${(ys[i] += moveY) + (options?.offsetY || 0)}px) scale(${scaleXs[i]}, ${scaleYs[i]})`) + `translate(${(xs[i] += moveX) + (options ?.offsetX || 0)}px, ${(ys[i] += moveY) + (options ?.offsetY || 0)}px) scale(${scaleXs[i]}, ${scaleYs[i]})`) ); }; const hideDragShowOriginalElements = () => { dragElements.map(dragElement => dragElement.parentNode === dragDiv && dragDiv.removeChild(dragElement)); - eles.map(ele => ele.parentElement && ele.parentElement?.className === dragData.dragDivName ? (ele.parentElement.hidden = false) : (ele.hidden = false)); + eles.map(ele => ele.parentElement && ele.parentElement ?.className === dragData.dragDivName ? (ele.parentElement.hidden = false) : (ele.hidden = false)); }; const endDrag = () => { document.removeEventListener("pointermove", moveHandler, true); @@ -376,14 +377,14 @@ export namespace DragManager { AbortDrag = () => { hideDragShowOriginalElements(); SelectionManager.SetIsDragging(false); - options?.dragComplete?.(new DragCompleteEvent(true, dragData)); + options ?.dragComplete ?.(new DragCompleteEvent(true, dragData)); endDrag(); }; const upHandler = (e: PointerEvent) => { hideDragShowOriginalElements(); dispatchDrag(eles, e, dragData, options, finishDrag); SelectionManager.SetIsDragging(false); - options?.dragComplete?.(new DragCompleteEvent(false, dragData)); + options ?.dragComplete ?.(new DragCompleteEvent(false, dragData)); endDrag(); }; document.addEventListener("pointermove", moveHandler, true); @@ -404,7 +405,7 @@ export namespace DragManager { }); if (target) { const complete = new DragCompleteEvent(false, dragData); - finishDrag?.(complete); + finishDrag ?.(complete); target.dispatchEvent( new CustomEvent("dashOnDrop", { diff --git a/src/client/views/nodes/WebBox.scss b/src/client/views/nodes/WebBox.scss index fbe9bf063..226103a53 100644 --- a/src/client/views/nodes/WebBox.scss +++ b/src/client/views/nodes/WebBox.scss @@ -90,4 +90,19 @@ width: 100%; margin-right: 10px; height: 100%; +} + +.touch-iframe-overlay { + width: 100%; + height: 100%; + position: absolute; + pointer-events: all; + + .indicator { + position: absolute; + + &.active { + background-color: rgba(0, 0, 0, 0.1); + } + } } \ No newline at end of file diff --git a/src/client/views/nodes/WebBox.tsx b/src/client/views/nodes/WebBox.tsx index c405dd9d4..ee5bf6f2f 100644 --- a/src/client/views/nodes/WebBox.tsx +++ b/src/client/views/nodes/WebBox.tsx @@ -39,6 +39,7 @@ export class WebBox extends DocAnnotatableComponent private _longPressSecondsHack?: NodeJS.Timeout; private _iframeRef = React.createRef(); + private _iframeIndicatorRef = React.createRef(); private _iframeDragRef = React.createRef(); @observable private _pressX: number = 0; @observable private _pressY: number = 0; @@ -63,39 +64,6 @@ export class WebBox extends DocAnnotatableComponent componentDidMount() { document.addEventListener("pointerup", this.onLongPressUp); document.addEventListener("pointermove", this.onLongPressMove); - // this._iframeRef.current?.contentWindow?.document.addEventListener("mousedown", (event: MouseEvent) => { - // console.log("clicked inside the iframe?"); - // }); - // const iframe = document.getElementById(this.props.Document.proto![Id]); - // if (iframe) { - // iframe.addEventListener('pointerdown', function (event) { - // const B = iframe.getBoundingClientRect(); - // const e = new CustomEvent('pointerdown', { bubbles: true, cancelable: false }); - // // e.clientX = e.clientX + B?.left; - // // e.clientY = e.clientY + B?.top; - // console.log("custom event pointer down"); - // iframe.dispatchEvent(e); - // }) - // } - // if (this._iframeRef.current) { - // console.log("resetting iframes events"); - // const self = this; - // this._iframeRef.current.addEventListener('pointermove', function (event) { - // const B = self._iframeRef.current?.getBoundingClientRect(); - // const e = new CustomEvent('pointermove', { bubbles: true, cancelable: false }); - // // e.clientX = e.clientX + B?.left; - // // e.clientY = e.clientY + B?.top; - // self._iframeRef.current?.dispatchEvent(e); - // }); - // this._iframeRef.current.addEventListener('pointerdown', function (event) { - // const B = self._iframeRef.current?.getBoundingClientRect(); - // const e = new CustomEvent('pointerdown', { bubbles: true, cancelable: false }); - // // e.clientX = e.clientX + B?.left; - // // e.clientY = e.clientY + B?.top; - // console.log("custom event pointer down"); - // self._iframeRef.current?.dispatchEvent(e); - // }) - // } } componentWillUnmount() { @@ -217,59 +185,75 @@ export class WebBox extends DocAnnotatableComponent } } - // TODO: make this actually a long press onLongPressDown = (e: React.PointerEvent) => { - - console.log("press down", e.clientX, e.clientX); this._pressX = e.clientX; this._pressY = e.clientY; - this._longPressSecondsHack = setTimeout(() => { - console.log("start the drag!!"); - const B = this._iframeRef.current?.getBoundingClientRect(); - const iframeDoc = this._iframeRef.current?.contentDocument; + + // find the pressed element in the iframe (currently only works if its an img) + let pressedElement: HTMLElement | undefined; + let pressedBound: ClientRect | undefined; + if (this._iframeRef.current) { + const B = this._iframeRef.current.getBoundingClientRect(); + const iframeDoc = this._iframeRef.current.contentDocument; if (B && iframeDoc) { - console.log("frame doc", iframeDoc); - console.log("get point", this._pressX, B.left, this._pressY, B.top); + // TODO: this only works when scale = 1 const element = iframeDoc.elementFromPoint(this._pressX - B.left, this._pressY - B.top); - console.log("found element", element); - if (element) { - e.stopPropagation(); - e.preventDefault(); - const clone = element.cloneNode(true) as HTMLElement; - - if (clone.nodeName === "IMG") { - const src = clone.getAttribute("src"); // TODO: may not always work - - if (src) { - const doc = Docs.Create.ImageDocument(src, { width: 300 }); - ImageUtils.ExtractExif(doc); - - console.log("start image drag", this._pressX, this._pressY, doc); - // document.dispatchEvent() - const dragData = new DragManager.DocumentDragData([doc]); - DragManager.StartDocumentDrag([clone], dragData, this._pressX, this._pressY); - } + if (element && element.nodeName === "IMG") { + pressedBound = element.getBoundingClientRect(); + pressedElement = element.cloneNode(true) as HTMLElement; + } + } + } + + // mark the pressed element + if (pressedElement && pressedBound) { + console.log("clones b", pressedElement.getBoundingClientRect(), pressedBound); + if (this._iframeIndicatorRef.current) { + this._iframeIndicatorRef.current.style.top = pressedBound.top + "px"; + this._iframeIndicatorRef.current.style.left = pressedBound.left + "px"; + this._iframeIndicatorRef.current.style.width = pressedBound.width + "px"; + this._iframeIndicatorRef.current.style.height = pressedBound.height + "px"; + this._iframeIndicatorRef.current.classList.add("active"); + } + } + + // start dragging the pressed element if long pressed + this._longPressSecondsHack = setTimeout(() => { + if (pressedElement && pressedBound) { + e.stopPropagation(); + e.preventDefault(); + if (pressedElement.nodeName === "IMG") { + const src = pressedElement.getAttribute("src"); // TODO: may not always work + if (src) { + const doc = Docs.Create.ImageDocument(src, { width: 300 }); + ImageUtils.ExtractExif(doc); + + // add clone to div so that dragging ghost is placed properly + if (this._iframeDragRef.current) this._iframeDragRef.current.appendChild(pressedElement); + + const dragData = new DragManager.DocumentDragData([doc]); + DragManager.StartDocumentDrag([pressedElement], dragData, this._pressX, this._pressY, { hideSource: true }); } } } }, 1500); - // e.stopPropagation(); - // e.preventDefault(); } onLongPressMove = (e: PointerEvent) => { - this._pressX = e.clientX; - this._pressY = e.clientY; + // this._pressX = e.clientX; + // this._pressY = e.clientY; } onLongPressUp = (e: PointerEvent) => { - console.log("press up"); if (this._longPressSecondsHack) { clearTimeout(this._longPressSecondsHack); - console.log("long press cancelled"); } - // e.stopPropagation(); - // e.preventDefault(); + if (this._iframeIndicatorRef.current) { + this._iframeIndicatorRef.current.classList.remove("active"); + } + if (this._iframeDragRef.current) { + while (this._iframeDragRef.current.firstChild) this._iframeDragRef.current.removeChild(this._iframeDragRef.current.firstChild); + } } @@ -300,9 +284,13 @@ export class WebBox extends DocAnnotatableComponent
{content}
-
- {!frozen ? (null) :
} - {/* onPointerDown={(e) => { this.onPrePointer(e); this.onLongPressDown(e) }} onPointerMove={this.onPrePointer} onPointerUp={(e) => { this.onPrePointer(e); }} />} */} + {!frozen ? (null) : +
+
+
+
+
+
} ); } render() { diff --git a/src/mobile/ImageUpload.tsx b/src/mobile/ImageUpload.tsx index 10bd78075..42dfd4e51 100644 --- a/src/mobile/ImageUpload.tsx +++ b/src/mobile/ImageUpload.tsx @@ -106,8 +106,6 @@ class Uploader extends React.Component { } -// Scripting.addGlobal(function uploadImageMobile() { return Uploader.onClick(); }); - // DocServer.init(window.location.protocol, window.location.hostname, 4321, "image upload"); (async () => { diff --git a/src/mobile/MobileInkOverlay.scss b/src/mobile/MobileInkOverlay.scss index 2e45d0441..0b4484519 100644 --- a/src/mobile/MobileInkOverlay.scss +++ b/src/mobile/MobileInkOverlay.scss @@ -1,10 +1,10 @@ .mobileInkOverlay { border: 5px dashed red; + background-color: rgba(0, 0, 0, .05); } .mobileInkOverlay-border { - background-color: rgba(0, 255, 0, .4); - position: absolute; + // background-color: rgba(0, 255, 0, .4); position: absolute; pointer-events: auto; cursor: pointer; diff --git a/src/mobile/MobileInkOverlay.tsx b/src/mobile/MobileInkOverlay.tsx index 9f810424a..db6cf21b4 100644 --- a/src/mobile/MobileInkOverlay.tsx +++ b/src/mobile/MobileInkOverlay.tsx @@ -20,6 +20,7 @@ export default class MobileInkOverlay extends React.Component { @observable private _height: number = 0; @observable private _x: number = -300; @observable private _y: number = -300; + @observable private _text: string = ""; @observable private _offsetX: number = 0; @observable private _offsetY: number = 0; @@ -32,21 +33,25 @@ export default class MobileInkOverlay extends React.Component { } initialSize(mobileWidth: number, mobileHeight: number) { - const maxWidth = window.innerWidth - 30; // TODO: may not be window ?? figure out how to not include library ???? + const maxWidth = window.innerWidth - 30; const maxHeight = window.innerHeight - 30; // -30 for padding - const scale = Math.min(maxWidth / mobileWidth, maxHeight / mobileHeight); - return { width: mobileWidth * scale, height: mobileHeight * scale, scale: scale }; + if (mobileWidth > maxWidth || mobileHeight > maxHeight) { + const scale = Math.min(maxWidth / mobileWidth, maxHeight / mobileHeight); + return { width: mobileWidth * scale, height: mobileHeight * scale, scale: scale }; + } + return { width: mobileWidth, height: mobileHeight, scale: 1 }; } @action initMobileInkOverlay(content: MobileInkOverlayContent) { - const { width, height } = content; + const { width, height, text } = content; const scaledSize = this.initialSize(width ? width : 0, height ? height : 0); this._width = scaledSize.width; this._height = scaledSize.height; - this._scale = scaledSize.scale; //scaledSize.scale; + this._scale = scaledSize.scale; this._x = 300; // TODO: center on screen this._y = 25; // TODO: center on screen + this._text = text ? text : ""; } @action @@ -73,7 +78,7 @@ export default class MobileInkOverlay extends React.Component { }; const target = document.elementFromPoint(this._x + 10, this._y + 10); - target?.dispatchEvent( + target ?.dispatchEvent( new CustomEvent("dashOnGesture", { bubbles: true, @@ -88,25 +93,13 @@ export default class MobileInkOverlay extends React.Component { } uploadDocument = async (content: MobileDocumentUploadContent) => { - const { docId, asCollection } = content; - console.log("receive upload document id", docId); + const { docId } = content; const doc = await DocServer.GetRefField(docId); if (doc && doc instanceof Doc) { - console.log("parsed upload document into doc", StrCast(doc.proto!.title)); - const target = document.elementFromPoint(this._x + 10, this._y + 10); - console.log("the target is", target); - - let uploadDocs = [doc]; - if (!asCollection) { - const children = await DocListCastAsync(doc.data); - console.log("uploading children", children); - uploadDocs = children ? children : []; - } - const dragData = new DragManager.DocumentDragData(uploadDocs); + const dragData = new DragManager.DocumentDragData([doc]); const complete = new DragManager.DragCompleteEvent(false, dragData); - console.log("the drag data is", dragData); if (target) { target.dispatchEvent( @@ -181,11 +174,11 @@ export default class MobileInkOverlay extends React.Component { zIndex: 30000, pointerEvents: "none", borderStyle: this._isDragging ? "solid" : "dashed", - backgroundColor: "rgba(255, 0, 0, 0.3)" } } ref={this._mainCont} > +

{this._text}

diff --git a/src/mobile/MobileInterface.scss b/src/mobile/MobileInterface.scss index 8b0ebcd53..8083e5760 100644 --- a/src/mobile/MobileInterface.scss +++ b/src/mobile/MobileInterface.scss @@ -1,15 +1,18 @@ .mobileInterface-inkInterfaceButtons { position: absolute; - top: -50px; + top: 0px; display: flex; justify-content: space-between; width: 100%; z-index: 9999; height: 50px; + + .mobileInterface-button { + height: 100%; + } } .mobileInterface-container { height: calc(100% - 50px); - margin-top: 50px; position: relative; } \ No newline at end of file diff --git a/src/mobile/MobileInterface.tsx b/src/mobile/MobileInterface.tsx index e21258c62..a3b956a15 100644 --- a/src/mobile/MobileInterface.tsx +++ b/src/mobile/MobileInterface.tsx @@ -34,6 +34,7 @@ import MarqueeOptionsMenu from '../client/views/collections/collectionFreeForm/M import GoogleAuthenticationManager from '../client/apis/GoogleAuthenticationManager'; import { listSpec } from '../new_fields/Schema'; import { Id } from '../new_fields/FieldSymbols'; +import { DocumentManager } from '../client/util/DocumentManager'; library.add(faLongArrowAltLeft); @@ -73,7 +74,6 @@ export default class MobileInterface extends React.Component { onSwitch && onSwitch(); this.renderView = renderView; - console.log("switching current view", renderView); } onSwitchInking = () => { @@ -87,22 +87,37 @@ export default class MobileInterface extends React.Component { }); } - onSwitchUpload = () => { + onSwitchUpload = async () => { + let width = 300; + let height = 300; + + // get width and height of the collection doc + if (this.mainContainer) { + const data = Cast(this.mainContainer.data, listSpec(Doc)); + if (data) { + const collectionDoc = await data[1]; // this should be the collection doc since the positions should be locked + const docView = DocumentManager.Instance.getDocumentView(collectionDoc); + if (docView) { + width = docView.nativeWidth ? docView.nativeWidth : 300; + height = docView.nativeHeight ? docView.nativeHeight : 300; + } + } + } DocServer.Mobile.dispatchOverlayTrigger({ enableOverlay: true, - width: 100, - height: 100 + width: width, + height: height, + text: "Documents uploaded from mobile will show here", }); } renderDefaultContent = () => { - console.log("rendering default content", this.mainContainer); if (this.mainContainer) { return { console.log("want to add doc to default content", StrCast(doc.title)); return false; }} + addDocument={returnFalse} addDocTab={returnFalse} pinToPres={emptyFunction} removeDocument={undefined} @@ -142,7 +157,6 @@ export default class MobileInterface extends React.Component { } shiftLeft = (e: React.MouseEvent) => { - console.log("shift left!"); DocServer.Mobile.dispatchOverlayPositionUpdate({ dx: -10 }); @@ -203,17 +217,16 @@ export default class MobileInterface extends React.Component { } } - upload = async (e: React.MouseEvent, asCollection: boolean) => { + upload = async (e: React.MouseEvent) => { if (this.mainContainer) { const data = Cast(this.mainContainer.data, listSpec(Doc)); if (data) { - const uploadDoc = await data[1]; // TODO: ensure this is the collection to upload - - console.log("UPLOADING DOCUMENT FROM MOBILE", uploadDoc[Id], StrCast(uploadDoc.proto!.title)); + const collectionDoc = await data[1]; // this should be the collection doc since the positions should be locked + const children = Cast(collectionDoc.data, listSpec(Doc), []); + const uploadDoc = children.length === 1 ? await children[0] : collectionDoc; if (uploadDoc) { DocServer.Mobile.dispatchMobileDocumentUpload({ docId: uploadDoc[Id], - asCollection: asCollection }); } } @@ -231,15 +244,14 @@ export default class MobileInterface extends React.Component {
- - +
{ console.log("want to add doc", StrCast(doc.title)); return false; }} + addDocument={returnFalse} addDocTab={returnFalse} pinToPres={emptyFunction} removeDocument={undefined} diff --git a/src/server/Message.ts b/src/server/Message.ts index 6dac37a46..b7bf2e81e 100644 --- a/src/server/Message.ts +++ b/src/server/Message.ts @@ -55,6 +55,7 @@ export interface MobileInkOverlayContent { readonly enableOverlay: boolean; readonly width?: number; readonly height?: number; + readonly text?: string; } export interface UpdateMobileInkOverlayPositionContent { @@ -65,7 +66,6 @@ export interface UpdateMobileInkOverlayPositionContent { export interface MobileDocumentUploadContent { readonly docId: string; - readonly asCollection: boolean; } export namespace MessageStore { diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 3e5953ac1..491685e18 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -102,9 +102,9 @@ export class CurrentUserUtils { { title: "use eraser", icon: "eraser", click: 'activateEraser(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "pink", activePen: doc }, { title: "use scrubber", icon: "eraser", click: 'activateScrubber(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "green", activePen: doc }, { title: "use drag", icon: "mouse-pointer", click: 'deactivateInk();this.activePen.pen = this;', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "white", activePen: doc }, - { title: "draw", icon: "pen-nib", click: 'switchMobileView(setupMobileInkingDoc, renderMobileInking, onSwitchMobileInking);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "red", activePen: doc }, + // { title: "draw", icon: "pen-nib", click: 'switchMobileView(setupMobileInkingDoc, renderMobileInking, onSwitchMobileInking);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "red", activePen: doc }, { title: "upload", icon: "upload", click: 'switchMobileView(setupMobileUploadDoc, renderMobileUpload, onSwitchMobileUpload);', backgroundColor: "orange" }, - { title: "upload", icon: "upload", click: 'uploadImageMobile();', backgroundColor: "cyan" }, + // { title: "upload", icon: "upload", click: 'uploadImageMobile();', backgroundColor: "cyan" }, ]; return docProtoData.filter(d => !buttons || !buttons.includes(d.title)).map(data => Docs.Create.FontIconDocument({ nativeWidth: 100, nativeHeight: 100, width: 100, height: 100, dropAction: data.click ? "copy" : undefined, title: data.title, icon: data.icon, ignoreClick: data.ignoreClick, @@ -138,9 +138,7 @@ export class CurrentUserUtils { } static setupMobileDoc(userDoc: Doc) { - const webDoc = Docs.Create.WebDocument("https://wikipedia.com", { title: "Mobile Upload Web", chromeStatus: "enabled" }); - - return userDoc.activeMoble ?? Docs.Create.MasonryDocument([webDoc, ...CurrentUserUtils.setupMobileButtons(userDoc)], { + return userDoc.activeMoble ?? Docs.Create.MasonryDocument(CurrentUserUtils.setupMobileButtons(userDoc), { columnWidth: 100, ignoreClick: true, lockedPosition: true, chromeStatus: "disabled", title: "buttons", autoHeight: true, yMargin: 5 }); } @@ -150,14 +148,15 @@ export class CurrentUserUtils { } static setupMobileUploadDoc(userDoc: Doc) { - const webDoc = Docs.Create.WebDocument("https://yahoo.com", { title: "Upload Images From the Web", chromeStatus: "enabled" }); - const uploadDoc = Docs.Create.StackingDocument([], { title: "Mobile Upload Collection", backgroundColor: "pink" }); - console.log("window size", window.innerWidth, window.innerHeight); - // return Docs.Create.StackingDocument([webDoc, uploadDoc], { - // columnWidth: window.innerWidth, //ignoreClick: true, lockedPosition: true, chromeStatus: "disabled", title: "Mobile Upload", autoHeight: true, yMargin: 5 - // }); - return Docs.Create.StackingDocument([webDoc, uploadDoc], {//...CurrentUserUtils.setupMobileButtons(userDoc)], { - columnWidth: 100, lockedPosition: true, chromeStatus: "disabled", title: "Upload", autoHeight: true, yMargin: 30 + const webDoc = Docs.Create.WebDocument("https://www.britannica.com/animal/cat", { + title: "Upload Images From the Web", chromeStatus: "enabled", lockedPosition: true + }); + const uploadDoc = Docs.Create.StackingDocument([], { + title: "Mobile Upload Collection", backgroundColor: "white", lockedPosition: true + }); + console.log(window.innerWidth, screen.width, window.devicePixelRatio); + return Docs.Create.StackingDocument([webDoc, uploadDoc], { + columnWidth: screen.width - 10, lockedPosition: true, chromeStatus: "disabled", title: "Upload", autoHeight: true, yMargin: 80, backgroundColor: "lightgray" }); } -- cgit v1.2.3-70-g09d2 From 07fa40d04c7cc7b0006da69648c13ee54bcd4d27 Mon Sep 17 00:00:00 2001 From: bob Date: Tue, 11 Feb 2020 10:45:05 -0500 Subject: fixes for chrome for presBox --- package-lock.json | 95 +++++++++++++--------- src/client/views/MainView.tsx | 1 - src/client/views/TemplateMenu.tsx | 2 +- src/client/views/collections/CollectionSubView.tsx | 1 - src/client/views/collections/CollectionView.tsx | 12 +-- .../CollectionMultirowView.tsx | 2 + src/client/views/nodes/FormattedTextBox.tsx | 3 +- src/client/views/nodes/ImageBox.tsx | 3 +- src/client/views/nodes/PresBox.tsx | 1 + src/client/views/nodes/VideoBox.tsx | 3 +- src/client/views/nodes/WebBox.tsx | 3 +- src/client/views/pdf/PDFViewer.tsx | 3 +- src/new_fields/documentSchemas.ts | 20 +++-- .../authentication/models/current_user_utils.ts | 4 +- 14 files changed, 85 insertions(+), 68 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/package-lock.json b/package-lock.json index a09df33da..2636d7113 100644 --- a/package-lock.json +++ b/package-lock.json @@ -657,7 +657,7 @@ }, "@types/passport": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@types/passport/-/passport-1.0.0.tgz", + "resolved": "https://registry.npmjs.org/@types/passport/-/passport-1.0.2.tgz", "integrity": "sha512-Pf39AYKf8q+YoONym3150cEwfUD66dtwHJWvbeOzKxnA0GZZ/vAXhNWv9vMhKyRQBQZiQyWQnhYBEBlKW6G8wg==", "requires": { "@types/express": "*" @@ -1997,7 +1997,7 @@ }, "util": { "version": "0.10.3", - "resolved": "https://registry.npmjs.org/util/-/util-0.10.3.tgz", + "resolved": "http://registry.npmjs.org/util/-/util-0.10.3.tgz", "integrity": "sha1-evsa/lCAUkZInj23/g7TeTNqwPk=", "dev": true, "requires": { @@ -2585,7 +2585,7 @@ }, "browserify-aes": { "version": "1.2.0", - "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", + "resolved": "http://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", "integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==", "requires": { "buffer-xor": "^1.0.3", @@ -2619,7 +2619,7 @@ }, "browserify-rsa": { "version": "4.0.1", - "resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz", + "resolved": "http://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz", "integrity": "sha1-IeCr+vbyApzy+vsTNWenAdQTVSQ=", "requires": { "bn.js": "^4.1.0", @@ -2783,7 +2783,7 @@ }, "camelcase-keys": { "version": "2.1.0", - "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz", + "resolved": "http://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz", "integrity": "sha1-MIvur/3ygRkFHvodkyITyRuPkuc=", "requires": { "camelcase": "^2.0.0", @@ -3576,7 +3576,7 @@ }, "create-hash": { "version": "1.2.0", - "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", + "resolved": "http://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==", "requires": { "cipher-base": "^1.0.1", @@ -3588,7 +3588,7 @@ }, "create-hmac": { "version": "1.1.7", - "resolved": "https://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz", + "resolved": "http://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz", "integrity": "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==", "requires": { "cipher-base": "^1.0.3", @@ -4126,7 +4126,7 @@ }, "diffie-hellman": { "version": "5.0.3", - "resolved": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz", + "resolved": "http://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz", "integrity": "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==", "requires": { "bn.js": "^4.1.0", @@ -5406,7 +5406,8 @@ }, "ansi-regex": { "version": "2.1.1", - "bundled": true + "bundled": true, + "optional": true }, "aproba": { "version": "1.2.0", @@ -5424,11 +5425,13 @@ }, "balanced-match": { "version": "1.0.0", - "bundled": true + "bundled": true, + "optional": true }, "brace-expansion": { "version": "1.1.11", "bundled": true, + "optional": true, "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -5441,15 +5444,18 @@ }, "code-point-at": { "version": "1.1.0", - "bundled": true + "bundled": true, + "optional": true }, "concat-map": { "version": "0.0.1", - "bundled": true + "bundled": true, + "optional": true }, "console-control-strings": { "version": "1.1.0", - "bundled": true + "bundled": true, + "optional": true }, "core-util-is": { "version": "1.0.2", @@ -5552,7 +5558,8 @@ }, "inherits": { "version": "2.0.4", - "bundled": true + "bundled": true, + "optional": true }, "ini": { "version": "1.3.5", @@ -5562,6 +5569,7 @@ "is-fullwidth-code-point": { "version": "1.0.0", "bundled": true, + "optional": true, "requires": { "number-is-nan": "^1.0.0" } @@ -5574,17 +5582,20 @@ "minimatch": { "version": "3.0.4", "bundled": true, + "optional": true, "requires": { "brace-expansion": "^1.1.7" } }, "minimist": { "version": "0.0.8", - "bundled": true + "bundled": true, + "optional": true }, "minipass": { "version": "2.9.0", "bundled": true, + "optional": true, "requires": { "safe-buffer": "^5.1.2", "yallist": "^3.0.0" @@ -5601,6 +5612,7 @@ "mkdirp": { "version": "0.5.1", "bundled": true, + "optional": true, "requires": { "minimist": "0.0.8" } @@ -5681,7 +5693,8 @@ }, "number-is-nan": { "version": "1.0.1", - "bundled": true + "bundled": true, + "optional": true }, "object-assign": { "version": "4.1.1", @@ -5691,6 +5704,7 @@ "once": { "version": "1.4.0", "bundled": true, + "optional": true, "requires": { "wrappy": "1" } @@ -5766,7 +5780,8 @@ }, "safe-buffer": { "version": "5.1.2", - "bundled": true + "bundled": true, + "optional": true }, "safer-buffer": { "version": "2.1.2", @@ -5796,6 +5811,7 @@ "string-width": { "version": "1.0.2", "bundled": true, + "optional": true, "requires": { "code-point-at": "^1.0.0", "is-fullwidth-code-point": "^1.0.0", @@ -5813,6 +5829,7 @@ "strip-ansi": { "version": "3.0.1", "bundled": true, + "optional": true, "requires": { "ansi-regex": "^2.0.0" } @@ -5851,11 +5868,13 @@ }, "wrappy": { "version": "1.0.2", - "bundled": true + "bundled": true, + "optional": true }, "yallist": { "version": "3.1.1", - "bundled": true + "bundled": true, + "optional": true } } }, @@ -6975,7 +6994,7 @@ }, "is-accessor-descriptor": { "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "resolved": "http://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", "requires": { "kind-of": "^3.0.2" @@ -7030,7 +7049,7 @@ }, "is-data-descriptor": { "version": "0.1.4", - "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "resolved": "http://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", "requires": { "kind-of": "^3.0.2" @@ -7717,7 +7736,7 @@ }, "load-json-file": { "version": "1.1.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", + "resolved": "http://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", "requires": { "graceful-fs": "^4.1.2", @@ -8035,7 +8054,7 @@ }, "media-typer": { "version": "0.3.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "resolved": "http://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=" }, "mem": { @@ -8067,7 +8086,7 @@ }, "meow": { "version": "3.7.0", - "resolved": "https://registry.npmjs.org/meow/-/meow-3.7.0.tgz", + "resolved": "http://registry.npmjs.org/meow/-/meow-3.7.0.tgz", "integrity": "sha1-cstmi0JSKCkKu/qFaJJYcwioAfs=", "requires": { "camelcase-keys": "^2.0.0", @@ -8242,7 +8261,7 @@ }, "mkdirp": { "version": "0.5.1", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "resolved": "http://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", "requires": { "minimist": "0.0.8" @@ -8575,7 +8594,7 @@ }, "next-tick": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.0.0.tgz", + "resolved": "http://registry.npmjs.org/next-tick/-/next-tick-1.0.0.tgz", "integrity": "sha1-yobR/ogoFpsBICCOPchCS524NCw=" }, "nice-try": { @@ -8658,7 +8677,7 @@ }, "semver": { "version": "5.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.3.0.tgz", + "resolved": "http://registry.npmjs.org/semver/-/semver-5.3.0.tgz", "integrity": "sha1-myzl094C0XxgEq0yaqa00M9U+U8=" }, "tar": { @@ -12258,7 +12277,7 @@ }, "os-homedir": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", + "resolved": "http://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", "integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M=" }, "os-locale": { @@ -12271,7 +12290,7 @@ }, "os-tmpdir": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "resolved": "http://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=" }, "osenv": { @@ -12511,7 +12530,7 @@ }, "path-is-absolute": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "resolved": "http://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" }, "path-is-inside": { @@ -13906,7 +13925,7 @@ }, "readable-stream": { "version": "2.3.6", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "resolved": "http://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", "requires": { "core-util-is": "~1.0.0", @@ -14348,7 +14367,7 @@ }, "safe-regex": { "version": "1.1.0", - "resolved": "https://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", + "resolved": "http://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", "requires": { "ret": "~0.1.10" @@ -14623,7 +14642,7 @@ }, "sha.js": { "version": "2.4.11", - "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", + "resolved": "http://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==", "requires": { "inherits": "^2.0.1", @@ -15480,7 +15499,7 @@ }, "string_decoder": { "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "resolved": "http://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "requires": { "safe-buffer": "~5.1.0" @@ -15510,7 +15529,7 @@ }, "strip-ansi": { "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", "requires": { "ansi-regex": "^2.0.0" @@ -15526,7 +15545,7 @@ }, "strip-eof": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", + "resolved": "http://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=" }, "strip-indent": { @@ -16298,7 +16317,7 @@ }, "tty-browserify": { "version": "0.0.0", - "resolved": "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.0.tgz", + "resolved": "http://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.0.tgz", "integrity": "sha1-oVe6QC2iTpv5V/mqadUk7tQpAaY=", "dev": true }, @@ -17751,7 +17770,7 @@ }, "wrap-ansi": { "version": "2.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", + "resolved": "http://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=", "requires": { "string-width": "^1.0.1", diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index a9e81093a..401a4b15c 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -493,7 +493,6 @@ export class MainView extends React.Component { fieldKey={"data"} annotationsKey={""} select={emptyFunction} - chromeCollapsed={true} active={returnFalse} isSelected={returnFalse} moveDocument={this.moveButtonDoc} diff --git a/src/client/views/TemplateMenu.tsx b/src/client/views/TemplateMenu.tsx index e03e4aa04..c9c6af054 100644 --- a/src/client/views/TemplateMenu.tsx +++ b/src/client/views/TemplateMenu.tsx @@ -81,7 +81,7 @@ export class TemplateMenu extends React.Component { toggleChrome = (): void => { this.props.docViews.map(dv => { const layout = Doc.Layout(dv.Document); - layout._chromeStatus = (layout._chromeStatus !== "disabled" ? "disabled" : "enabled"); + layout._chromeStatus = (layout._chromeStatus !== "disabled" ? "disabled" : StrCast(layout._replacedChrome, "enabled")); }); } diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index d71bad647..293a8491a 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -33,7 +33,6 @@ export interface CollectionViewProps extends FieldViewProps { PanelWidth: () => number; PanelHeight: () => number; VisibleHeight?: () => number; - chromeCollapsed: boolean; setPreviewCursor?: (func: (x: number, y: number, drag: boolean) => void) => void; fieldKey: string; } diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index 1c4818957..8dd844711 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -115,7 +115,7 @@ export class CollectionView extends Touchable { // chrome status is one of disabled, collapsed, or visible. this determines initial state from document // chrome status may also be view-mode, in reference to stacking view's toggle mode. it is essentially disabled mode, but prevents the toggle button from showing up on the left sidebar. const chromeStatus = this.props.Document._chromeStatus; - if (chromeStatus && (chromeStatus === "disabled" || chromeStatus === "collapsed")) { + if (chromeStatus && (chromeStatus === "disabled" || chromeStatus === "collapsed" || chromeStatus === "replaced")) { runInAction(() => this._collapsed = true); } }); @@ -175,14 +175,14 @@ export class CollectionView extends Touchable { } private SubViewHelper = (type: CollectionViewType, renderProps: CollectionRenderProps) => { - const props = { ...this.props, ...renderProps, chromeCollapsed: this._collapsed, ChromeHeight: this.chromeHeight, CollectionView: this, annotationsKey: "" }; + const props = { ...this.props, ...renderProps, ChromeHeight: this.chromeHeight, CollectionView: this, annotationsKey: "" }; switch (type) { case CollectionViewType.Schema: return (); case CollectionViewType.Docking: return (); case CollectionViewType.Tree: return (); - case CollectionViewType.Staff: return (); - case CollectionViewType.Multicolumn: return (); - case CollectionViewType.Multirow: return (); + case CollectionViewType.Staff: return (); + case CollectionViewType.Multicolumn: return (); + case CollectionViewType.Multirow: return (); case CollectionViewType.Linear: { return (); } case CollectionViewType.Carousel: { return (); } case CollectionViewType.Stacking: { this.props.Document.singleColumn = true; return (); } @@ -201,7 +201,7 @@ export class CollectionView extends Touchable { private SubView = (type: CollectionViewType, renderProps: CollectionRenderProps) => { // currently cant think of a reason for collection docking view to have a chrome. mind may change if we ever have nested docking views -syip - const chrome = this.props.Document._chromeStatus === "disabled" || type === CollectionViewType.Docking ? (null) : + const chrome = this.props.Document._chromeStatus === "disabled" || this.props.Document._chromeStatus === "replaced" || type === CollectionViewType.Docking ? (null) : ; return [chrome, this.SubViewHelper(type, renderProps)]; } diff --git a/src/client/views/collections/collectionMulticolumn/CollectionMultirowView.tsx b/src/client/views/collections/collectionMulticolumn/CollectionMultirowView.tsx index ff7c4998f..ec05443e5 100644 --- a/src/client/views/collections/collectionMulticolumn/CollectionMultirowView.tsx +++ b/src/client/views/collections/collectionMulticolumn/CollectionMultirowView.tsx @@ -258,6 +258,8 @@ export class CollectionMultirowView extends CollectionSubView(MultirowDocument) return (
diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 881d80dda..09aaad9df 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -1123,8 +1123,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & CollectionView={undefined} ScreenToLocalTransform={this.sidebarScreenToLocal} renderDepth={this.props.renderDepth + 1} - ContainingCollectionDoc={this.props.ContainingCollectionDoc} - chromeCollapsed={true}> + ContainingCollectionDoc={this.props.ContainingCollectionDoc}>
this.toggleSidebar()} />
} diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index 99c6fde34..db9800de4 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -436,8 +436,7 @@ export class ImageBox extends DocAnnotatableComponent + ContainingCollectionDoc={this.props.ContainingCollectionDoc}> {this.contentFunc}
); diff --git a/src/client/views/nodes/PresBox.tsx b/src/client/views/nodes/PresBox.tsx index 2afdc190d..85017d3d4 100644 --- a/src/client/views/nodes/PresBox.tsx +++ b/src/client/views/nodes/PresBox.tsx @@ -40,6 +40,7 @@ export class PresBox extends React.Component { componentDidMount() { const userDoc = CurrentUserUtils.UserDocument; this.props.Document._forceRenderEngine = "timeline"; + this.props.Document._replacedChrome = "replaced"; this._slideshowReaction = reaction(() => this.props.Document._viewType, (slideshow) => { if (slideshow === CollectionViewType.Stacking || slideshow === undefined) { diff --git a/src/client/views/nodes/VideoBox.tsx b/src/client/views/nodes/VideoBox.tsx index d12a8d151..6695e04c3 100644 --- a/src/client/views/nodes/VideoBox.tsx +++ b/src/client/views/nodes/VideoBox.tsx @@ -354,8 +354,7 @@ export class VideoBox extends DocAnnotatableComponent + ContainingCollectionDoc={this.props.ContainingCollectionDoc}> {this.contentFunc}
diff --git a/src/client/views/nodes/WebBox.tsx b/src/client/views/nodes/WebBox.tsx index a48dc286e..7e49d957d 100644 --- a/src/client/views/nodes/WebBox.tsx +++ b/src/client/views/nodes/WebBox.tsx @@ -211,8 +211,7 @@ export class WebBox extends DocAnnotatableComponent CollectionView={undefined} ScreenToLocalTransform={this.props.ScreenToLocalTransform} renderDepth={this.props.renderDepth + 1} - ContainingCollectionDoc={this.props.ContainingCollectionDoc} - chromeCollapsed={true}> + ContainingCollectionDoc={this.props.ContainingCollectionDoc}> {() => [this.content]}
); diff --git a/src/client/views/pdf/PDFViewer.tsx b/src/client/views/pdf/PDFViewer.tsx index a7c1990e9..4f50be5b0 100644 --- a/src/client/views/pdf/PDFViewer.tsx +++ b/src/client/views/pdf/PDFViewer.tsx @@ -651,8 +651,7 @@ export class PDFViewer extends DocAnnotatableComponent + ContainingCollectionDoc={this.props.ContainingCollectionView?.props.Document}>
; } diff --git a/src/new_fields/documentSchemas.ts b/src/new_fields/documentSchemas.ts index 1707524cb..aac6d4e3e 100644 --- a/src/new_fields/documentSchemas.ts +++ b/src/new_fields/documentSchemas.ts @@ -10,22 +10,24 @@ export const documentSchema = createSchema({ title: "string", // document title (can be on either data document or layout) dropAction: "string", // override specifying what should happen when this document is dropped (can be "alias" or "copy") childDropAction: "string", // specify the override for what should happen when the child of a collection is dragged from it and dropped (can be "alias" or "copy") - _nativeWidth: "number", // native width of document which determines how much document contents are scaled when the document's width is set - _nativeHeight: "number", // " - _width: "number", // width of document in its container's coordinate system - _height: "number", // " + _nativeWidth: "number", // native width of document which determines how much document contents are scaled when the document's width is set + _nativeHeight: "number", // " + _width: "number", // width of document in its container's coordinate system + _height: "number", // " _freeformLayoutEngine: "string",// the string ID for the layout engine to use to layout freeform view documents - _LODdisable: "boolean", // whether to disbale LOD switching for CollectionFreeFormViews + _LODdisable: "boolean", // whether to disbale LOD switching for CollectionFreeFormViews _pivotField: "string", // specifies which field should be used as the timeline/pivot axis + _replacedChrome: "string", // what the default chrome is replaced with. Currently only supports the value of 'replaced' for PresBox's. + _chromeStatus: "string", // determines the state of the collection chrome. values allowed are 'replaced', 'enabled', 'disabled', 'collapsed' color: "string", // foreground color of document backgroundColor: "string", // background color of document opacity: "number", // opacity of document - creationDate: DateField, // when the document was created + creationDate: DateField, // when the document was created links: listSpec(Doc), // computed (readonly) list of links associated with this document removeDropProperties: listSpec("string"), // properties that should be removed from the alias/copy/etc of this document when it is dropped onClick: ScriptField, // script to run when document is clicked (can be overriden by an onClick prop) - onPointerDown: ScriptField, // script to run when document is clicked (can be overriden by an onClick prop) - onPointerUp: ScriptField, // script to run when document is clicked (can be overriden by an onClick prop) + onPointerDown: ScriptField, // script to run when document is clicked (can be overriden by an onClick prop) + onPointerUp: ScriptField, // script to run when document is clicked (can be overriden by an onClick prop) onDragStart: ScriptField, // script to run when document is dragged (without being selected). the script should return the Doc to be dropped. dragFactory: Doc, // the document that serves as the "template" for the onDragStart script. ie, to drag out copies of the dragFactory document. ignoreAspect: "boolean", // whether aspect ratio should be ignored when laying out or manipulating the document @@ -36,7 +38,7 @@ export const documentSchema = createSchema({ treeViewOpen: "boolean", // flag denoting whether the documents sub-tree (contents) is visible or hidden treeViewExpandedView: "string", // name of field whose contents are being displayed as the document's subtree preventTreeViewOpen: "boolean", // ignores the treeViewOpen flag (for allowing a view to not be slaved to other views of the document) - currentTimecode: "number", // current play back time of a temporal document (video / audio) + currentTimecode: "number", // current play back time of a temporal document (video / audio) maximizeLocation: "string", // flag for where to place content when following a click interaction (e.g., onRight, inPlace, inTab) lockedPosition: "boolean", // whether the document can be moved (dragged) lockedTransform: "boolean", // whether the document can be panned/zoomed diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 3a2a0f513..0185017ec 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -48,7 +48,7 @@ export class CurrentUserUtils { // setup the "creator" buttons for the sidebar-- eg. the default set of draggable document creation tools static setupCreatorButtons(doc: Doc, buttons?: string[]) { const notes = CurrentUserUtils.setupNoteTypes(doc); - const emptyPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, _chromeStatus: "enabled", showTitle: "title", boxShadow: "0 0" }); + const emptyPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, _chromeStatus: "replaced", showTitle: "title", boxShadow: "0 0" }); const emptyCollection = Docs.Create.FreeformDocument([], { _nativeWidth: undefined, _nativeHeight: undefined, _LODdisable: true, _width: 150, _height: 100, title: "freeform" }); doc.noteTypes = Docs.Create.TreeDocument(notes, { title: "Note Types", _height: 75 }); doc.activePen = doc; @@ -270,7 +270,7 @@ export class CurrentUserUtils { // the initial presentation Doc to use static setupDefaultPresentation(doc: Doc) { - doc.curPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, _chromeStatus: "enabled", showTitle: "title", boxShadow: "0 0" }); + doc.curPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, _chromeStatus: "replaced", showTitle: "title", boxShadow: "0 0" }); } static setupMobileUploads(doc: Doc) { -- cgit v1.2.3-70-g09d2 From 47b939e9799da2f57047a15113c116d8ba31ce5e Mon Sep 17 00:00:00 2001 From: vellichora Date: Tue, 11 Feb 2020 10:49:25 -0500 Subject: fixed some small errors --- package-lock.json | 56 ++++++++-------------- package.json | 4 +- src/client/views/nodes/WebBox.tsx | 2 +- src/mobile/MobileInkOverlay.tsx | 5 +- src/mobile/MobileInterface.tsx | 2 - .../authentication/models/current_user_utils.ts | 4 +- 6 files changed, 28 insertions(+), 45 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/package-lock.json b/package-lock.json index 833710fe7..5492f7dbf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5682,8 +5682,7 @@ }, "ansi-regex": { "version": "2.1.1", - "bundled": true, - "optional": true + "bundled": true }, "aproba": { "version": "1.2.0", @@ -5701,13 +5700,11 @@ }, "balanced-match": { "version": "1.0.0", - "bundled": true, - "optional": true + "bundled": true }, "brace-expansion": { "version": "1.1.11", "bundled": true, - "optional": true, "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -5720,18 +5717,15 @@ }, "code-point-at": { "version": "1.1.0", - "bundled": true, - "optional": true + "bundled": true }, "concat-map": { "version": "0.0.1", - "bundled": true, - "optional": true + "bundled": true }, "console-control-strings": { "version": "1.1.0", - "bundled": true, - "optional": true + "bundled": true }, "core-util-is": { "version": "1.0.2", @@ -5834,8 +5828,7 @@ }, "inherits": { "version": "2.0.4", - "bundled": true, - "optional": true + "bundled": true }, "ini": { "version": "1.3.5", @@ -5845,7 +5838,6 @@ "is-fullwidth-code-point": { "version": "1.0.0", "bundled": true, - "optional": true, "requires": { "number-is-nan": "^1.0.0" } @@ -5858,20 +5850,17 @@ "minimatch": { "version": "3.0.4", "bundled": true, - "optional": true, "requires": { "brace-expansion": "^1.1.7" } }, "minimist": { "version": "0.0.8", - "bundled": true, - "optional": true + "bundled": true }, "minipass": { "version": "2.9.0", "bundled": true, - "optional": true, "requires": { "safe-buffer": "^5.1.2", "yallist": "^3.0.0" @@ -5888,7 +5877,6 @@ "mkdirp": { "version": "0.5.1", "bundled": true, - "optional": true, "requires": { "minimist": "0.0.8" } @@ -5969,8 +5957,7 @@ }, "number-is-nan": { "version": "1.0.1", - "bundled": true, - "optional": true + "bundled": true }, "object-assign": { "version": "4.1.1", @@ -5980,7 +5967,6 @@ "once": { "version": "1.4.0", "bundled": true, - "optional": true, "requires": { "wrappy": "1" } @@ -6056,8 +6042,7 @@ }, "safe-buffer": { "version": "5.1.2", - "bundled": true, - "optional": true + "bundled": true }, "safer-buffer": { "version": "2.1.2", @@ -6087,7 +6072,6 @@ "string-width": { "version": "1.0.2", "bundled": true, - "optional": true, "requires": { "code-point-at": "^1.0.0", "is-fullwidth-code-point": "^1.0.0", @@ -6105,7 +6089,6 @@ "strip-ansi": { "version": "3.0.1", "bundled": true, - "optional": true, "requires": { "ansi-regex": "^2.0.0" } @@ -6144,13 +6127,11 @@ }, "wrappy": { "version": "1.0.2", - "bundled": true, - "optional": true + "bundled": true }, "yallist": { "version": "3.1.1", - "bundled": true, - "optional": true + "bundled": true } } }, @@ -14665,19 +14646,22 @@ "dev": true }, "resilient-server-session": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/resilient-server-session/-/resilient-server-session-1.1.2.tgz", - "integrity": "sha512-eLoXxTc5bFOYH2JejSCYc2O8emoo80p2zOuwVVWVoK6/2NJBzLP8Yl7kU8m7tJDrOoqDSZGghsVD5ob9BbUgAQ==", + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/resilient-server-session/-/resilient-server-session-1.1.9.tgz", + "integrity": "sha512-XSVujTyJOQMACllXUvWOSHY4GK4JI6aECjCrQR0UBvd2+hdjM1euffspn2b+7M0fepo+bJ71YrAOA9M34ChBZw==", "requires": { "@types/chai": "^4.2.7", + "@types/express": "^4.17.2", "@types/mocha": "^5.2.7", "@types/node": "^10.12.30", "@types/request-promise": "^4.1.42", "@types/uuid": "^3.4.6", "chai": "^4.2.0", "colors": "^1.4.0", + "express": "^4.17.1", "jsonschema": "^1.2.5", "mocha": "^7.0.0", + "request": "^2.88.0", "request-promise": "^4.2.5", "typescript": "^3.7.4", "uuid": "^3.3.3" @@ -14842,9 +14826,9 @@ } }, "mocha": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-7.0.0.tgz", - "integrity": "sha512-CirsOPbO3jU86YKjjMzFLcXIb5YiGLUrjrXFHoJ3e2z9vWiaZVCZQ2+gtRGMPWF+nFhN6AWwLM/juzAQ6KRkbA==", + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-7.0.1.tgz", + "integrity": "sha512-9eWmWTdHLXh72rGrdZjNbG3aa1/3NRPpul1z0D979QpEnFdCG0Q5tv834N+94QEN2cysfV72YocQ3fn87s70fg==", "requires": { "ansi-colors": "3.2.3", "browser-stdout": "1.3.1", diff --git a/package.json b/package.json index 67b9b1630..6a2b5fac4 100644 --- a/package.json +++ b/package.json @@ -233,7 +233,7 @@ "readline": "^1.3.0", "request": "^2.88.0", "request-promise": "^4.2.5", - "resilient-server-session": "^1.1.2", + "resilient-server-session": "^1.1.9", "rimraf": "^3.0.0", "serializr": "^1.5.4", "sharp": "^0.23.4", @@ -253,4 +253,4 @@ "xoauth2": "^1.2.0", "youtube": "^0.1.0" } -} \ No newline at end of file +} diff --git a/src/client/views/nodes/WebBox.tsx b/src/client/views/nodes/WebBox.tsx index 082a9a965..d486253b8 100644 --- a/src/client/views/nodes/WebBox.tsx +++ b/src/client/views/nodes/WebBox.tsx @@ -222,7 +222,7 @@ export class WebBox extends DocAnnotatableComponent if (pressedElement.nodeName === "IMG") { const src = pressedElement.getAttribute("src"); // TODO: may not always work if (src) { - const doc = Docs.Create.ImageDocument(src, { width: 300 }); + const doc = Docs.Create.ImageDocument(src, { _width: 300 }); ImageUtils.ExtractExif(doc); // add clone to div so that dragging ghost is placed properly diff --git a/src/mobile/MobileInkOverlay.tsx b/src/mobile/MobileInkOverlay.tsx index db6cf21b4..4dde3a075 100644 --- a/src/mobile/MobileInkOverlay.tsx +++ b/src/mobile/MobileInkOverlay.tsx @@ -78,7 +78,7 @@ export default class MobileInkOverlay extends React.Component { }; const target = document.elementFromPoint(this._x + 10, this._y + 10); - target ?.dispatchEvent( + target?.dispatchEvent( new CustomEvent("dashOnGesture", { bubbles: true, @@ -112,7 +112,8 @@ export default class MobileInkOverlay extends React.Component { complete: complete, altKey: false, metaKey: false, - ctrlKey: false + ctrlKey: false, + shiftKey: false } } ) diff --git a/src/mobile/MobileInterface.tsx b/src/mobile/MobileInterface.tsx index d0954a84b..07ee611ee 100644 --- a/src/mobile/MobileInterface.tsx +++ b/src/mobile/MobileInterface.tsx @@ -206,7 +206,6 @@ export default class MobileInterface extends React.Component { ContentScaling={returnOne} whenActiveChanged={returnFalse} ScreenToLocalTransform={Transform.Identity} - ruleProvider={undefined} renderDepth={0} ContainingCollectionView={undefined} ContainingCollectionDoc={undefined}> @@ -254,7 +253,6 @@ export default class MobileInterface extends React.Component { addDocTab={returnFalse} pinToPres={emptyFunction} removeDocument={undefined} - ruleProvider={undefined} onClick={undefined} ScreenToLocalTransform={Transform.Identity} ContentScaling={returnOne} diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 4a765e8d3..aa9f3649e 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -156,14 +156,14 @@ export class CurrentUserUtils { static setupMobileUploadDoc(userDoc: Doc) { const webDoc = Docs.Create.WebDocument("https://www.britannica.com/animal/cat", { - title: "Upload Images From the Web", chromeStatus: "enabled", lockedPosition: true + title: "Upload Images From the Web", _chromeStatus: "enabled", lockedPosition: true }); const uploadDoc = Docs.Create.StackingDocument([], { title: "Mobile Upload Collection", backgroundColor: "white", lockedPosition: true }); console.log(window.innerWidth, screen.width, window.devicePixelRatio); return Docs.Create.StackingDocument([webDoc, uploadDoc], { - columnWidth: screen.width - 10, lockedPosition: true, chromeStatus: "disabled", title: "Upload", autoHeight: true, yMargin: 80, backgroundColor: "lightgray" + columnWidth: screen.width - 10, lockedPosition: true, _chromeStatus: "disabled", title: "Upload", _autoHeight: true, _yMargin: 80, backgroundColor: "lightgray" }); } -- cgit v1.2.3-70-g09d2 From be02a5529f472507512a127cd8de5cde300eff88 Mon Sep 17 00:00:00 2001 From: bob Date: Tue, 11 Feb 2020 14:19:56 -0500 Subject: added ability to pass a Layout as a prop. changed presentations to use layout props. fixed creating a template for just an empty collection representing one field. --- src/client/util/DropConverter.ts | 7 +- src/client/views/DocComponent.tsx | 5 +- .../views/collections/CollectionStackingView.tsx | 20 +++-- .../CollectionFreeFormLayoutEngines.tsx | 9 ++- .../views/nodes/ContentFittingDocumentView.tsx | 6 +- src/client/views/nodes/DocumentContentsView.tsx | 4 +- src/client/views/nodes/DocumentView.tsx | 3 +- src/client/views/nodes/FieldView.tsx | 1 + src/client/views/nodes/PresBox.tsx | 28 +------ .../views/presentationview/PresElementBox.tsx | 90 +++++++++++----------- src/new_fields/Doc.ts | 7 +- .../authentication/models/current_user_utils.ts | 5 +- 12 files changed, 94 insertions(+), 91 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/util/DropConverter.ts b/src/client/util/DropConverter.ts index d0f1d86cb..3c7caa60b 100644 --- a/src/client/util/DropConverter.ts +++ b/src/client/util/DropConverter.ts @@ -8,7 +8,7 @@ import { ScriptField, ComputedField } from "../../new_fields/ScriptField"; import { RichTextField } from "../../new_fields/RichTextField"; import { ImageField } from "../../new_fields/URLField"; -export function makeTemplate(doc: Doc): boolean { +export function makeTemplate(doc: Doc, first: boolean = true): boolean { const layoutDoc = doc.layout instanceof Doc && doc.layout.isTemplateForField ? doc.layout : doc; const layout = StrCast(layoutDoc.layout).match(/fieldKey={'[^']*'}/)![0]; const fieldKey = layout.replace("fieldKey={'", "").replace(/'}$/, ""); @@ -18,9 +18,12 @@ export function makeTemplate(doc: Doc): boolean { if (!StrCast(d.title).startsWith("-")) { any = Doc.MakeMetadataFieldTemplate(d, Doc.GetProto(layoutDoc)) || any; } else if (d.type === DocumentType.COL || d.data instanceof RichTextField) { - any = makeTemplate(d) || any; + any = makeTemplate(d, false) || any; } }); + if (!docs.length && first) { + any = Doc.MakeMetadataFieldTemplate(doc, Doc.GetProto(layoutDoc)) || any; + } if (layoutDoc[fieldKey] instanceof RichTextField || layoutDoc[fieldKey] instanceof ImageField) { if (!StrCast(layoutDoc.title).startsWith("-")) { any = Doc.MakeMetadataFieldTemplate(layoutDoc, Doc.GetProto(layoutDoc)); diff --git a/src/client/views/DocComponent.tsx b/src/client/views/DocComponent.tsx index ce48e1215..0bf944f22 100644 --- a/src/client/views/DocComponent.tsx +++ b/src/client/views/DocComponent.tsx @@ -1,4 +1,4 @@ -import { Doc } from '../../new_fields/Doc'; +import { Doc, Opt } from '../../new_fields/Doc'; import { Touchable } from './Touchable'; import { computed, action, observable } from 'mobx'; import { Cast } from '../../new_fields/Types'; @@ -11,12 +11,13 @@ import { PositionDocument } from '../../new_fields/documentSchemas'; /// DocComponent returns a generic React base class used by views that don't have any data extensions (e.g.,CollectionFreeFormDocumentView, DocumentView, ButtonBox) interface DocComponentProps { Document: Doc; + LayoutDoc?: () => Opt; } export function DocComponent

(schemaCtor: (doc: Doc) => T) { class Component extends Touchable

{ //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); } - @computed get layoutDoc() { return PositionDocument(Doc.Layout(this.props.Document)); } + @computed get layoutDoc() { return PositionDocument(Doc.Layout(this.props.Document, this.props.LayoutDoc?.())); } } return Component; } diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index 21c34d047..d21ae32bc 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -55,7 +55,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { this._docXfs.length = 0; return docs.map((d, i) => { const height = () => this.getDocHeight(d); - const width = () => Math.min(d._nativeWidth && !d.ignoreAspect && !this.props.Document.fillColumn ? d[WidthSym]() : Number.MAX_VALUE, this.columnWidth / this.numGroupColumns); + const width = () => this.getDocWidth(d); const dref = React.createRef(); const dxf = () => this.getDocTransform(d, dref.current!); this._docXfs.push({ dxf: dxf, width: width, height: height }); @@ -154,11 +154,12 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { @computed get onClickHandler() { return ScriptCast(this.Document.onChildClick); } getDisplayDoc(doc: Doc, dataDoc: Doc | undefined, dxf: () => Transform, width: () => number) { - const layoutDoc = Doc.Layout(doc); + const layoutDoc = Doc.Layout(doc, this.props.childLayoutTemplate?.()); const height = () => this.getDocHeight(doc); return doc) { pinToPres={this.props.pinToPres}> ; } + + getDocWidth(d?: Doc) { + if (!d) return 0; + const layoutDoc = Doc.Layout(d, this.props.childLayoutTemplate?.()); + const nw = NumCast(layoutDoc._nativeWidth); + return Math.min(nw && !d.ignoreAspect && !this.props.Document.fillColumn ? d[WidthSym]() : Number.MAX_VALUE, this.columnWidth / this.numGroupColumns); + } getDocHeight(d?: Doc) { if (!d) return 0; - const layoutDoc = Doc.Layout(d); + let layoutDoc = Doc.Layout(d, this.props.childLayoutTemplate?.()); const nw = NumCast(layoutDoc._nativeWidth); const nh = NumCast(layoutDoc._nativeHeight); let wid = this.columnWidth / (this.isStackingView ? this.numGroupColumns : 1); if (!layoutDoc.ignoreAspect && !layoutDoc._fitWidth && nw && nh) { const aspect = nw && nh ? nh / nw : 1; - if (!(d._nativeWidth && !layoutDoc.ignoreAspect && this.props.Document.fillColumn)) wid = Math.min(layoutDoc[WidthSym](), wid); + if (!(!layoutDoc.ignoreAspect && this.props.Document.fillColumn)) wid = Math.min(layoutDoc[WidthSym](), wid); return wid * aspect; } - return layoutDoc._fitWidth ? !layoutDoc._nativeHeight ? this.props.PanelHeight() - 2 * this.yMargin : - Math.min(wid * NumCast(layoutDoc.scrollHeight, NumCast(layoutDoc._nativeHeight)) / NumCast(layoutDoc._nativeWidth, 1), this.props.PanelHeight() - 2 * this.yMargin) : layoutDoc[HeightSym](); + return layoutDoc._fitWidth ? !nh ? this.props.PanelHeight() - 2 * this.yMargin : + Math.min(wid * NumCast(layoutDoc.scrollHeight, nh) / (nw || 1), this.props.PanelHeight() - 2 * this.yMargin) : layoutDoc[HeightSym](); } columnDividerDown = (e: React.PointerEvent) => { diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx index b86cbbdbd..050ca8347 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx @@ -43,6 +43,9 @@ export interface ViewDefResult { bounds?: ViewDefBounds; } function toLabel(target: FieldResult) { + if (typeof target === "number" || Number(target)) { + return Number(target).toFixed(2).toString(); + } if (target instanceof ObjectField || target instanceof RefField) { return target[ToString](); } @@ -254,10 +257,10 @@ export function computeTimelineLayout( let prevKey = Math.floor(minTime); if (sortedKeys.length && scaling * (sortedKeys[0] - prevKey) > 25) { - groupNames.push({ type: "text", text: prevKey.toString(), x: x, y: 0, height: fontHeight, fontSize, payload: undefined }); + groupNames.push({ type: "text", text: toLabel(prevKey), x: x, y: 0, height: fontHeight, fontSize, payload: undefined }); } if (!sortedKeys.length && curTime !== undefined) { - groupNames.push({ type: "text", text: curTime.toString(), x: (curTime - minTime) * scaling, zIndex: 1000, color: "orange", y: 0, height: fontHeight, fontSize, payload: undefined }); + groupNames.push({ type: "text", text: toLabel(curTime), x: (curTime - minTime) * scaling, zIndex: 1000, color: "orange", y: 0, height: fontHeight, fontSize, payload: undefined }); } const pivotAxisWidth = NumCast(pivotDoc.pivotTimeWidth, panelDim[1] / 2.5); @@ -265,7 +268,7 @@ export function computeTimelineLayout( let zind = 0; sortedKeys.forEach(key => { if (curTime !== undefined && curTime > prevKey && curTime <= key) { - groupNames.push({ type: "text", text: curTime.toString(), x: (curTime - minTime) * scaling, y: 0, zIndex: 1000, color: "orange", height: fontHeight, fontSize, payload: key }); + groupNames.push({ type: "text", text: toLabel(curTime), x: (curTime - minTime) * scaling, y: 0, zIndex: 1000, color: "orange", height: fontHeight, fontSize, payload: key }); } const keyDocs = pivotDateGroups.get(key)!; x += scaling * (key - prevKey); diff --git a/src/client/views/nodes/ContentFittingDocumentView.tsx b/src/client/views/nodes/ContentFittingDocumentView.tsx index bd1b6166f..671f5b96e 100644 --- a/src/client/views/nodes/ContentFittingDocumentView.tsx +++ b/src/client/views/nodes/ContentFittingDocumentView.tsx @@ -2,7 +2,7 @@ import React = require("react"); import { action, computed } from "mobx"; import { observer } from "mobx-react"; import "react-table/react-table.css"; -import { Doc } from "../../../new_fields/Doc"; +import { Doc, Opt } from "../../../new_fields/Doc"; import { ComputedField, ScriptField } from "../../../new_fields/ScriptField"; import { NumCast, StrCast } from "../../../new_fields/Types"; import { emptyFunction, returnEmptyString, returnOne } from "../../../Utils"; @@ -18,6 +18,7 @@ import { TraceMobx } from "../../../new_fields/util"; interface ContentFittingDocumentViewProps { Document?: Doc; DataDocument?: Doc; + LayoutDoc?: () => Opt; LibraryPath: Doc[]; childDocs?: Doc[]; renderDepth: number; @@ -42,7 +43,7 @@ interface ContentFittingDocumentViewProps { @observer export class ContentFittingDocumentView extends React.Component{ public get displayName() { return "DocumentView(" + this.props.Document?.title + ")"; } // this makes mobx trace() statements more descriptive - private get layoutDoc() { return this.props.Document && Doc.Layout(this.props.Document); } + private get layoutDoc() { return this.props.Document && (this.props.LayoutDoc?.() || Doc.Layout(this.props.Document)); } private get nativeWidth() { return NumCast(this.layoutDoc?._nativeWidth, this.props.PanelWidth()); } private get nativeHeight() { return NumCast(this.layoutDoc?._nativeHeight, this.props.PanelHeight()); } @computed get scaling() { @@ -97,6 +98,7 @@ export class ContentFittingDocumentView extends React.Component; Document: Doc; DataDoc?: Doc; + LayoutDoc?: () => Opt; LibraryPath: Doc[]; fitToBox?: boolean; onClick?: ScriptField; @@ -834,6 +834,7 @@ export class DocumentView extends DocComponent(Docu ContainingCollectionDoc={this.props.ContainingCollectionDoc} Document={this.props.Document} DataDoc={this.props.DataDoc} + LayoutDoc={this.props.LayoutDoc} fitToBox={this.props.fitToBox} LibraryPath={this.props.LibraryPath} addDocument={this.props.addDocument} diff --git a/src/client/views/nodes/FieldView.tsx b/src/client/views/nodes/FieldView.tsx index 7544a5b77..8250f41f3 100644 --- a/src/client/views/nodes/FieldView.tsx +++ b/src/client/views/nodes/FieldView.tsx @@ -43,6 +43,7 @@ export interface FieldViewProps { setVideoBox?: (player: VideoBox) => void; ContentScaling: () => number; ChromeHeight?: () => number; + childLayoutTemplate?: () => Opt; } @observer diff --git a/src/client/views/nodes/PresBox.tsx b/src/client/views/nodes/PresBox.tsx index 85017d3d4..d4a47c159 100644 --- a/src/client/views/nodes/PresBox.tsx +++ b/src/client/views/nodes/PresBox.tsx @@ -20,6 +20,7 @@ import { ContextMenuProps } from "../ContextMenuItem"; import { InkingControl } from "../InkingControl"; import { FieldView, FieldViewProps } from './FieldView'; import "./PresBox.scss"; +import { PrefetchProxy } from "../../../new_fields/Proxy"; library.add(faArrowLeft); library.add(faArrowRight); @@ -34,35 +35,14 @@ library.add(faEdit); export class PresBox extends React.Component { public static LayoutString(fieldKey: string) { return FieldView.LayoutString(PresBox, fieldKey); } _childReaction: IReactionDisposer | undefined; - _slideshowReaction: IReactionDisposer | undefined; @observable _isChildActive = false; - componentDidMount() { - const userDoc = CurrentUserUtils.UserDocument; this.props.Document._forceRenderEngine = "timeline"; this.props.Document._replacedChrome = "replaced"; - this._slideshowReaction = reaction(() => this.props.Document._viewType, - (slideshow) => { - if (slideshow === CollectionViewType.Stacking || slideshow === undefined) { - let presTemp = Cast(userDoc.presentationTemplate, Doc); - if (presTemp instanceof Promise) { - presTemp.then(presTemp => this.props.Document.childLayout = presTemp); - } - else if (presTemp === undefined) { - presTemp = userDoc.presentationTemplate = Docs.Create.PresElementBoxDocument({ backgroundColor: "transparent", _xMargin: 5, isTemplateDoc: true, isTemplateForField: "data" }); - } - else { - this.props.Document.childLayout = presTemp; - } - } else { - this.props.Document.childLayout = undefined; - } - }, { fireImmediately: true }); this._childReaction = reaction(() => this.childDocs.slice(), (children) => children.forEach((child, i) => child.presentationIndex = i), { fireImmediately: true }); } componentWillUnmount() { this._childReaction?.(); - this._slideshowReaction?.(); } @computed get childDocs() { return DocListCast(this.props.Document[this.props.fieldKey]); } @@ -376,7 +356,6 @@ export class PresBox extends React.Component { doc.presBox = this.props.Document; doc.presBoxKey = this.props.fieldKey; doc.collapsedHeight = hgt; - doc._nativeWidth = doc._nativeHeight = undefined; const curScale = NumCast(doc.viewScale, null); if (curScale === undefined) { doc.viewScale = 1; @@ -402,6 +381,8 @@ export class PresBox extends React.Component { this.props.Document._viewType = Number(e.target.selectedOptions[0].value); this.updateMinimize(e, Number(this.props.Document._viewType)); }); + + childLayoutTemplate = () => this.props.Document._viewType === CollectionViewType.Stacking ? Cast(Doc.UserDoc().presentationTemplate, Doc, null) : undefined; render() { const mode = NumCast(this.props.Document._viewType, CollectionViewType.Invalid); this.initializeScaleViews(this.childDocs, mode); @@ -425,8 +406,7 @@ export class PresBox extends React.Component {

{mode !== CollectionViewType.Invalid ? - : (null) } diff --git a/src/client/views/presentationview/PresElementBox.tsx b/src/client/views/presentationview/PresElementBox.tsx index 52773d466..888707ee3 100644 --- a/src/client/views/presentationview/PresElementBox.tsx +++ b/src/client/views/presentationview/PresElementBox.tsx @@ -2,19 +2,18 @@ import { library } from '@fortawesome/fontawesome-svg-core'; import { faFile as fileRegular } from '@fortawesome/free-regular-svg-icons'; import { faArrowDown, faArrowUp, faFile as fileSolid, faFileDownload, faLocationArrow, faSearch } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { action, computed, reaction, IReactionDisposer } from "mobx"; +import { action, computed, IReactionDisposer, reaction } from "mobx"; import { observer } from "mobx-react"; -import { Doc, DocListCast } from "../../../new_fields/Doc"; +import { Doc } from "../../../new_fields/Doc"; import { documentSchema } from '../../../new_fields/documentSchemas'; import { Id } from "../../../new_fields/FieldSymbols"; import { createSchema, makeInterface } from '../../../new_fields/Schema'; -import { Cast, NumCast, StrCast } from "../../../new_fields/Types"; -import { emptyFunction, returnFalse, emptyPath } from "../../../Utils"; -import { DocumentType } from "../../documents/DocumentTypes"; +import { Cast, NumCast } from "../../../new_fields/Types"; +import { emptyFunction, emptyPath, returnFalse } from "../../../Utils"; import { Transform } from "../../util/Transform"; import { CollectionViewType } from '../collections/CollectionView'; +import { DocExtendableComponent } from '../DocComponent'; import { ContentFittingDocumentView } from '../nodes/ContentFittingDocumentView'; -import { DocComponent, DocExtendableComponent } from '../DocComponent'; import { FieldView, FieldViewProps } from '../nodes/FieldView'; import "./PresElementBox.scss"; import React = require("react"); @@ -50,15 +49,16 @@ export class PresElementBox extends DocExtendableComponent [this.originalLayout.embedOpen, this.originalLayout.collapsedHeight], - params => this.originalLayout._height = NumCast(params[1]) + (Number(params[0]) ? 100 : 0), { fireImmediately: true }); + this._heightDisposer = reaction(() => [this.presElementDoc.embedOpen, this.presElementDoc.collapsedHeight], + params => this.presLayoutDoc._height = NumCast(params[1]) + (Number(params[0]) ? 100 : 0), { fireImmediately: true }); } componentWillUnmount() { this._heightDisposer?.(); @@ -71,13 +71,13 @@ export class PresElementBox extends DocExtendableComponent { e.stopPropagation(); - this.originalLayout.hideTillShownButton = !this.originalLayout.hideTillShownButton; - if (!this.originalLayout.hideTillShownButton) { + this.presElementDoc.hideTillShownButton = !this.presElementDoc.hideTillShownButton; + if (!this.presElementDoc.hideTillShownButton) { if (this.indexInPres >= this.currentIndex && this.targetDoc) { this.targetDoc.opacity = 1; } } else { - if (this.presentationDoc.presStatus && this.indexInPres > this.currentIndex && this.targetDoc) { + if (this.presBoxDoc.presStatus && this.indexInPres > this.currentIndex && this.targetDoc) { this.targetDoc.opacity = 0; } } @@ -91,14 +91,14 @@ export class PresElementBox extends DocExtendableComponent { e.stopPropagation(); - this.originalLayout.hideAfterButton = !this.originalLayout.hideAfterButton; - if (!this.originalLayout.hideAfterButton) { + this.presElementDoc.hideAfterButton = !this.presElementDoc.hideAfterButton; + if (!this.presElementDoc.hideAfterButton) { if (this.indexInPres <= this.currentIndex && this.targetDoc) { this.targetDoc.opacity = 1; } } else { - if (this.originalLayout.fadeButton) this.originalLayout.fadeButton = false; - if (this.presentationDoc.presStatus && this.indexInPres < this.currentIndex && this.targetDoc) { + if (this.presElementDoc.fadeButton) this.presElementDoc.fadeButton = false; + if (this.presBoxDoc.presStatus && this.indexInPres < this.currentIndex && this.targetDoc) { this.targetDoc.opacity = 0; } } @@ -112,14 +112,14 @@ export class PresElementBox extends DocExtendableComponent { e.stopPropagation(); - this.originalLayout.fadeButton = !this.originalLayout.fadeButton; - if (!this.originalLayout.fadeButton) { + this.presElementDoc.fadeButton = !this.presElementDoc.fadeButton; + if (!this.presElementDoc.fadeButton) { if (this.indexInPres <= this.currentIndex && this.targetDoc) { this.targetDoc.opacity = 1; } } else { - this.originalLayout.hideAfterButton = false; - if (this.presentationDoc.presStatus && (this.indexInPres < this.currentIndex) && this.targetDoc) { + this.presElementDoc.hideAfterButton = false; + if (this.presBoxDoc.presStatus && (this.indexInPres < this.currentIndex) && this.targetDoc) { this.targetDoc.opacity = 0.5; } } @@ -131,11 +131,11 @@ export class PresElementBox extends DocExtendableComponent { e.stopPropagation(); - this.originalLayout.navButton = !this.originalLayout.navButton; - if (this.originalLayout.navButton) { - this.originalLayout.showButton = false; + this.presElementDoc.navButton = !this.presElementDoc.navButton; + if (this.presElementDoc.navButton) { + this.presElementDoc.showButton = false; if (this.currentIndex === this.indexInPres) { - this.props.focus(this.originalLayout); + this.props.focus(this.presElementDoc); } } } @@ -147,13 +147,13 @@ export class PresElementBox extends DocExtendableComponent { e.stopPropagation(); - this.originalLayout.showButton = !this.originalLayout.showButton; - if (!this.originalLayout.showButton) { - this.originalLayout.viewScale = 1; + this.presElementDoc.showButton = !this.presElementDoc.showButton; + if (!this.presElementDoc.showButton) { + this.presElementDoc.viewScale = 1; } else { - this.originalLayout.navButton = false; + this.presElementDoc.navButton = false; if (this.currentIndex === this.indexInPres) { - this.props.focus(this.originalLayout); + this.props.focus(this.presElementDoc); } } } @@ -162,14 +162,14 @@ export class PresElementBox extends DocExtendableComponent [xCord, yCord]; - embedHeight = () => this.props.PanelHeight() - NumCast(this.originalLayout.collapsedHeight); + embedHeight = () => this.props.PanelHeight() - NumCast(this.presElementDoc.collapsedHeight); embedWidth = () => this.props.PanelWidth() - 20; /** * The function that is responsible for rendering the a preview or not for this * presentation element. */ renderEmbeddedInline = () => { - return !this.originalLayout.embedOpen || !this.targetDoc ? (null) : + return !this.presElementDoc.embedOpen || !this.targetDoc ? (null) :
{ this.props.focus(this.originalLayout); e.stopPropagation(); }}> + onClick={e => { this.props.focus(this.presElementDoc); e.stopPropagation(); }}> {treecontainer ? (null) : <> {`${this.indexInPres + 1}. ${this.targetDoc?.title}`} - +
} - - - - - - - + + + + + + +
{this.renderEmbeddedInline()} diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index 1636f4ee7..447dbe3b0 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -701,8 +701,11 @@ export namespace Doc { } // the document containing the view layout information - will be the Document itself unless the Document has - // a layout field. In that case, all layout information comes from there unless overriden by Document - export function Layout(doc: Doc): Doc { return doc[LayoutSym] || doc; } + // a layout field or 'layout' is given. + export function Layout(doc: Doc, layout?: Doc): Doc { + const overrideLayout = layout && Cast(doc["data-layout[" + layout[Id] + "]"], Doc, null); + return overrideLayout || doc[LayoutSym] || doc; + } export function SetLayout(doc: Doc, layout: Doc | string) { doc[StrCast(doc.layoutKey, "layout")] = layout; } export function LayoutField(doc: Doc) { return doc[StrCast(doc.layoutKey, "layout")]; } export function LayoutFieldKey(doc: Doc): string { return StrCast(Doc.Layout(doc).layout).split("'")[1]; } diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 0185017ec..ce4f94d83 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -48,7 +48,7 @@ export class CurrentUserUtils { // setup the "creator" buttons for the sidebar-- eg. the default set of draggable document creation tools static setupCreatorButtons(doc: Doc, buttons?: string[]) { const notes = CurrentUserUtils.setupNoteTypes(doc); - const emptyPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, _chromeStatus: "replaced", showTitle: "title", boxShadow: "0 0" }); + const emptyPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, _LODdisable: true, _chromeStatus: "replaced", showTitle: "title", boxShadow: "0 0" }); const emptyCollection = Docs.Create.FreeformDocument([], { _nativeWidth: undefined, _nativeHeight: undefined, _LODdisable: true, _width: 150, _height: 100, title: "freeform" }); doc.noteTypes = Docs.Create.TreeDocument(notes, { title: "Note Types", _height: 75 }); doc.activePen = doc; @@ -270,7 +270,8 @@ export class CurrentUserUtils { // the initial presentation Doc to use static setupDefaultPresentation(doc: Doc) { - doc.curPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, _chromeStatus: "replaced", showTitle: "title", boxShadow: "0 0" }); + doc.presentationTemplate = new PrefetchProxy(Docs.Create.PresElementBoxDocument({ backgroundColor: "transparent", _xMargin: 5, _height: 46, isTemplateDoc: true, isTemplateForField: "data" })); + doc.curPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, _LODdisable: true, _chromeStatus: "replaced", showTitle: "title", boxShadow: "0 0" }); } static setupMobileUploads(doc: Doc) { -- cgit v1.2.3-70-g09d2 From 864cba561db8e26240b093da7ab524e76c8823d1 Mon Sep 17 00:00:00 2001 From: andrewdkim Date: Tue, 11 Feb 2020 22:47:23 -0500 Subject: small fixes for mobile remote upload --- package-lock.json | 41 ++++++++++++++++------ src/client/views/nodes/WebBox.tsx | 12 +++++-- src/mobile/MobileInkOverlay.scss | 5 +-- src/mobile/MobileInterface.scss | 2 +- src/mobile/MobileInterface.tsx | 8 +++-- src/server/DashSession/DashSessionAgent.ts | 21 ++++++----- .../authentication/models/current_user_utils.ts | 3 +- src/server/index.ts | 2 +- 8 files changed, 63 insertions(+), 31 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/package-lock.json b/package-lock.json index 5492f7dbf..1741b50dc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5682,7 +5682,8 @@ }, "ansi-regex": { "version": "2.1.1", - "bundled": true + "bundled": true, + "optional": true }, "aproba": { "version": "1.2.0", @@ -5700,11 +5701,13 @@ }, "balanced-match": { "version": "1.0.0", - "bundled": true + "bundled": true, + "optional": true }, "brace-expansion": { "version": "1.1.11", "bundled": true, + "optional": true, "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -5717,15 +5720,18 @@ }, "code-point-at": { "version": "1.1.0", - "bundled": true + "bundled": true, + "optional": true }, "concat-map": { "version": "0.0.1", - "bundled": true + "bundled": true, + "optional": true }, "console-control-strings": { "version": "1.1.0", - "bundled": true + "bundled": true, + "optional": true }, "core-util-is": { "version": "1.0.2", @@ -5828,7 +5834,8 @@ }, "inherits": { "version": "2.0.4", - "bundled": true + "bundled": true, + "optional": true }, "ini": { "version": "1.3.5", @@ -5838,6 +5845,7 @@ "is-fullwidth-code-point": { "version": "1.0.0", "bundled": true, + "optional": true, "requires": { "number-is-nan": "^1.0.0" } @@ -5850,17 +5858,20 @@ "minimatch": { "version": "3.0.4", "bundled": true, + "optional": true, "requires": { "brace-expansion": "^1.1.7" } }, "minimist": { "version": "0.0.8", - "bundled": true + "bundled": true, + "optional": true }, "minipass": { "version": "2.9.0", "bundled": true, + "optional": true, "requires": { "safe-buffer": "^5.1.2", "yallist": "^3.0.0" @@ -5877,6 +5888,7 @@ "mkdirp": { "version": "0.5.1", "bundled": true, + "optional": true, "requires": { "minimist": "0.0.8" } @@ -5957,7 +5969,8 @@ }, "number-is-nan": { "version": "1.0.1", - "bundled": true + "bundled": true, + "optional": true }, "object-assign": { "version": "4.1.1", @@ -5967,6 +5980,7 @@ "once": { "version": "1.4.0", "bundled": true, + "optional": true, "requires": { "wrappy": "1" } @@ -6042,7 +6056,8 @@ }, "safe-buffer": { "version": "5.1.2", - "bundled": true + "bundled": true, + "optional": true }, "safer-buffer": { "version": "2.1.2", @@ -6072,6 +6087,7 @@ "string-width": { "version": "1.0.2", "bundled": true, + "optional": true, "requires": { "code-point-at": "^1.0.0", "is-fullwidth-code-point": "^1.0.0", @@ -6089,6 +6105,7 @@ "strip-ansi": { "version": "3.0.1", "bundled": true, + "optional": true, "requires": { "ansi-regex": "^2.0.0" } @@ -6127,11 +6144,13 @@ }, "wrappy": { "version": "1.0.2", - "bundled": true + "bundled": true, + "optional": true }, "yallist": { "version": "3.1.1", - "bundled": true + "bundled": true, + "optional": true } } }, diff --git a/src/client/views/nodes/WebBox.tsx b/src/client/views/nodes/WebBox.tsx index d486253b8..6cae4e878 100644 --- a/src/client/views/nodes/WebBox.tsx +++ b/src/client/views/nodes/WebBox.tsx @@ -193,9 +193,17 @@ export class WebBox extends DocAnnotatableComponent const B = this._iframeRef.current.getBoundingClientRect(); const iframeDoc = this._iframeRef.current.contentDocument; if (B && iframeDoc) { - // TODO: this only works when scale = 1 + // check if there is selected text + const selectedText = iframeDoc.getSelection(); + if (selectedText && selectedText.toString.length > -1) { + + } + console.log("selectedText", selectedText ? selectedText.toString() : ""); + + // TODO: this only works when scale = 1 as it is currently only inteded for mobile upload const element = iframeDoc.elementFromPoint(this._pressX - B.left, this._pressY - B.top); - if (element && element.nodeName === "IMG") { + console.log("found element", element, element && element.nodeName); + if (element && element.nodeName) {//} === "IMG") { pressedBound = element.getBoundingClientRect(); pressedElement = element.cloneNode(true) as HTMLElement; } diff --git a/src/mobile/MobileInkOverlay.scss b/src/mobile/MobileInkOverlay.scss index 0b4484519..b9c1fb146 100644 --- a/src/mobile/MobileInkOverlay.scss +++ b/src/mobile/MobileInkOverlay.scss @@ -1,10 +1,11 @@ .mobileInkOverlay { - border: 5px dashed red; + border: 10px dashed red; background-color: rgba(0, 0, 0, .05); } .mobileInkOverlay-border { - // background-color: rgba(0, 255, 0, .4); position: absolute; + // background-color: rgba(0, 255, 0, .4); + position: absolute; pointer-events: auto; cursor: pointer; diff --git a/src/mobile/MobileInterface.scss b/src/mobile/MobileInterface.scss index 8083e5760..d0849dbc7 100644 --- a/src/mobile/MobileInterface.scss +++ b/src/mobile/MobileInterface.scss @@ -13,6 +13,6 @@ } .mobileInterface-container { - height: calc(100% - 50px); + height: 100%; position: relative; } \ No newline at end of file diff --git a/src/mobile/MobileInterface.tsx b/src/mobile/MobileInterface.tsx index 07ee611ee..83410b99d 100644 --- a/src/mobile/MobileInterface.tsx +++ b/src/mobile/MobileInterface.tsx @@ -3,7 +3,7 @@ import { observer } from 'mobx-react'; import { computed, action, observable } from 'mobx'; import { CurrentUserUtils } from '../server/authentication/models/current_user_utils'; import { FieldValue, Cast, StrCast } from '../new_fields/Types'; -import { Doc } from '../new_fields/Doc'; +import { Doc, DocListCast } from '../new_fields/Doc'; import { Docs } from '../client/documents/Documents'; import { CollectionView } from '../client/views/collections/CollectionView'; import { DocumentView } from '../client/views/nodes/DocumentView'; @@ -220,8 +220,10 @@ export default class MobileInterface extends React.Component { const data = Cast(this.mainContainer.data, listSpec(Doc)); if (data) { const collectionDoc = await data[1]; // this should be the collection doc since the positions should be locked - const children = Cast(collectionDoc.data, listSpec(Doc), []); - const uploadDoc = children.length === 1 ? await children[0] : collectionDoc; + const children = DocListCast(collectionDoc.data); + const uploadDoc = children.length === 1 ? children[0] : Docs.Create.StackingDocument(children, { + title: "Mobile Upload Collection", backgroundColor: "white", lockedPosition: true, _width: 300, _height: 300 + }); if (uploadDoc) { DocServer.Mobile.dispatchMobileDocumentUpload({ docId: uploadDoc[Id], diff --git a/src/server/DashSession/DashSessionAgent.ts b/src/server/DashSession/DashSessionAgent.ts index c55e01243..44f77c049 100644 --- a/src/server/DashSession/DashSessionAgent.ts +++ b/src/server/DashSession/DashSessionAgent.ts @@ -25,15 +25,18 @@ export class DashSessionAgent extends AppliedSessionAgent { * The core method invoked when the single master thread is initialized. * Installs event hooks, repl commands and additional IPC listeners. */ - protected async initializeMonitor(monitor: Monitor, sessionKey: string): Promise { - await this.dispatchSessionPassword(sessionKey); - monitor.addReplCommand("pull", [], () => monitor.exec("git pull")); - monitor.addReplCommand("solr", [/start|stop|index/], this.executeSolrCommand); - monitor.addReplCommand("backup", [], this.backup); - monitor.addReplCommand("debug", [/\S+\@\S+/], async ([to]) => this.dispatchZippedDebugBackup(to)); - monitor.on("backup", this.backup); - monitor.on("debug", async ({ to }) => this.dispatchZippedDebugBackup(to)); - monitor.coreHooks.onCrashDetected(this.dispatchCrashReport); + // protected async initializeMonitor(monitor: Monitor, sessionKey: string): Promise { + protected async initializeMonitor(monitor: Monitor): Promise { + + // await this.dispatchSessionPassword(sessionKey); + // monitor.addReplCommand("pull", [], () => monitor.exec("git pull")); + // monitor.addReplCommand("solr", [/start|stop|index/], this.executeSolrCommand); + // monitor.addReplCommand("backup", [], this.backup); + // monitor.addReplCommand("debug", [/\S+\@\S+/], async ([to]) => this.dispatchZippedDebugBackup(to)); + // monitor.on("backup", this.backup); + // monitor.on("debug", async ({ to }) => this.dispatchZippedDebugBackup(to)); + // monitor.coreHooks.onCrashDetected(this.dispatchCrashReport); + return ""; } /** diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index aa9f3649e..6c916689a 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -161,9 +161,8 @@ export class CurrentUserUtils { const uploadDoc = Docs.Create.StackingDocument([], { title: "Mobile Upload Collection", backgroundColor: "white", lockedPosition: true }); - console.log(window.innerWidth, screen.width, window.devicePixelRatio); return Docs.Create.StackingDocument([webDoc, uploadDoc], { - columnWidth: screen.width - 10, lockedPosition: true, _chromeStatus: "disabled", title: "Upload", _autoHeight: true, _yMargin: 80, backgroundColor: "lightgray" + _width: screen.width, lockedPosition: true, _chromeStatus: "disabled", title: "Upload", _autoHeight: true, _yMargin: 80, backgroundColor: "lightgray" }); } diff --git a/src/server/index.ts b/src/server/index.ts index 313a2f0e2..55ba71dba 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -141,7 +141,7 @@ export async function launchServer() { * So, the 'else' clause is exactly what we've always run when executing npm start. */ if (process.env.RELEASE) { - (sessionAgent = new DashSessionAgent()).launch(); + // (sessionAgent = new DashSessionAgent()).launch(); } else { launchServer(); } -- cgit v1.2.3-70-g09d2 From d1b9049fe50e401ac1a33177babd0cfa4b32f6a0 Mon Sep 17 00:00:00 2001 From: andrewdkim Date: Wed, 12 Feb 2020 03:37:51 -0500 Subject: can select text from web node and upload from mobile --- src/client/util/DragManager.ts | 1 - src/client/views/nodes/FormattedTextBox.tsx | 28 ++++++------ src/client/views/nodes/WebBox.tsx | 50 +++++++++++++++------- src/mobile/MobileInterface.tsx | 20 +++++++++ .../authentication/models/current_user_utils.ts | 1 + 5 files changed, 70 insertions(+), 30 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index bf64e0bdb..5d4b8fc8a 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -289,7 +289,6 @@ export namespace DragManager { if (!ele.parentNode) dragDiv.appendChild(ele); const dragElement = ele.parentNode === dragDiv ? ele : ele.cloneNode(true) as HTMLElement; const rect = ele.getBoundingClientRect(); - console.log("boudning", rect); const scaleX = rect.width / ele.offsetWidth, scaleY = rect.height / ele.offsetHeight; xs.push(rect.left); diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 0d97c3029..213af43c6 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -700,7 +700,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & setTimeout(async () => { const targetField = Doc.LayoutFieldKey(pdfDoc); const targetAnnotations = await DocListCastAsync(pdfDoc[DataSym][targetField + "-annotations"]);// bcz: better to have the PDF's view handle updating its own annotations - targetAnnotations?.push(pdfRegion); + targetAnnotations ?.push(pdfRegion); }); const link = DocUtils.MakeLink({ doc: this.props.Document, ctx: this.props.ContainingCollectionDoc }, { doc: pdfRegion, ctx: pdfDoc }, "note on " + pdfDoc.title, "pasted PDF link"); @@ -742,14 +742,14 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & const rtfField = Cast(this.props.Document._textTemplate || this.dataDoc[fieldKey], RichTextField); if (this.ProseRef) { const self = this; - this._editorView?.destroy(); + this._editorView ?.destroy(); this._editorView = new EditorView(this.ProseRef, { - state: rtfField?.Data ? EditorState.fromJSON(config, JSON.parse(rtfField.Data)) : EditorState.create(config), + state: rtfField ?.Data ? EditorState.fromJSON(config, JSON.parse(rtfField.Data)) : EditorState.create(config), handleScrollToSelection: (editorView) => { const ref = editorView.domAtPos(editorView.state.selection.from); let refNode = ref.node as any; while (refNode && !("getBoundingClientRect" in refNode)) refNode = refNode.parentElement; - const r1 = refNode?.getBoundingClientRect(); + const r1 = refNode ?.getBoundingClientRect(); const r3 = self._ref.current!.getBoundingClientRect(); if (r1.top < r3.top || r1.top > r3.bottom) { r1 && (self._scrollRef.current!.scrollTop += (r1.top - r3.top) * self.props.ScreenToLocalTransform().Scale); @@ -848,11 +848,11 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & this.tryUpdateHeight(); // see if we need to preserve the insertion point - const prosediv = this.ProseRef?.children?.[0] as any; - const keeplocation = prosediv?.keeplocation; + const prosediv = this.ProseRef ?.children ?.[0] as any; + const keeplocation = prosediv ?.keeplocation; prosediv && (prosediv.keeplocation = undefined); - const pos = this._editorView?.state.selection.$from.pos || 1; - keeplocation && setTimeout(() => this._editorView?.dispatch(this._editorView?.state.tr.setSelection(TextSelection.create(this._editorView.state.doc, pos)))); + const pos = this._editorView ?.state.selection.$from.pos || 1; + keeplocation && setTimeout(() => this._editorView ?.dispatch(this._editorView ?.state.tr.setSelection(TextSelection.create(this._editorView.state.doc, pos)))); // jump rich text menu to this textbox const { current } = this._ref; @@ -876,13 +876,13 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & if ((this._editorView!.root as any).getSelection().isCollapsed) { // this is a hack to allow the cursor to be placed at the end of a document when the document ends in an inline dash comment. Apparently Chrome on Windows has a bug/feature which breaks this when clicking after the end of the text. const pcords = this._editorView!.posAtCoords({ left: e.clientX, top: e.clientY }); const node = pcords && this._editorView!.state.doc.nodeAt(pcords.pos); // get what prosemirror thinks the clicked node is (if it's null, then we didn't click on any text) - if (pcords && node?.type === this._editorView!.state.schema.nodes.dashComment) { + if (pcords && node ?.type === this._editorView!.state.schema.nodes.dashComment) { this._editorView!.dispatch(this._editorView!.state.tr.setSelection(TextSelection.create(this._editorView!.state.doc, pcords.pos + 2))); e.preventDefault(); } if (!node && this.ProseRef) { const lastNode = this.ProseRef.children[this.ProseRef.children.length - 1].children[this.ProseRef.children[this.ProseRef.children.length - 1].children.length - 1]; // get the last prosemirror div - if (e.clientY > lastNode?.getBoundingClientRect().bottom) { // if we clicked below the last prosemirror div, then set the selection to be the end of the document + if (e.clientY > lastNode ?.getBoundingClientRect().bottom) { // if we clicked below the last prosemirror div, then set the selection to be the end of the document this._editorView!.dispatch(this._editorView!.state.tr.setSelection(TextSelection.create(this._editorView!.state.doc, this._editorView!.state.doc.content.size))); } } @@ -939,7 +939,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & for (let off = 1; off < 100; off++) { const pos = this._editorView!.posAtCoords({ left: x + off, top: y }); const node = pos && this._editorView!.state.doc.nodeAt(pos.pos); - if (node?.type === schema.nodes.list_item) { + if (node ?.type === schema.nodes.list_item) { list_node = node; break; } @@ -984,7 +984,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & const self = FormattedTextBox; return new Plugin({ view(newView) { - RichTextMenu.Instance.changeView(newView); + RichTextMenu.Instance && RichTextMenu.Instance.changeView(newView); return RichTextMenu.Instance; } }); @@ -1021,7 +1021,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & } if (e.key === "Escape") { this._editorView!.dispatch(state.tr.setSelection(TextSelection.create(state.doc, state.selection.from, state.selection.from))); - (document.activeElement as any).blur?.(); + (document.activeElement as any).blur ?.(); SelectionManager.DeselectAll(); } e.stopPropagation(); @@ -1043,7 +1043,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & @action tryUpdateHeight(limitHeight?: number) { - let scrollHeight = this._ref.current?.scrollHeight; + let scrollHeight = this._ref.current ?.scrollHeight; if (!this.layoutDoc.animateToPos && this.layoutDoc._autoHeight && scrollHeight && getComputedStyle(this._ref.current!.parentElement!).top === "0px") { // if top === 0, then the text box is growing upward (as the overlay caption) which doesn't contribute to the height computation if (limitHeight && scrollHeight > limitHeight) { diff --git a/src/client/views/nodes/WebBox.tsx b/src/client/views/nodes/WebBox.tsx index 6cae4e878..0b7c3eda9 100644 --- a/src/client/views/nodes/WebBox.tsx +++ b/src/client/views/nodes/WebBox.tsx @@ -24,6 +24,7 @@ import { documentSchema } from "../../../new_fields/documentSchemas"; import { Id } from "../../../new_fields/FieldSymbols"; import { DragManager } from "../../util/DragManager"; import { ImageUtils } from "../../util/Import & Export/ImageUtils"; +import { select } from "async"; library.add(faStickyNote); @@ -189,30 +190,37 @@ export class WebBox extends DocAnnotatableComponent // find the pressed element in the iframe (currently only works if its an img) let pressedElement: HTMLElement | undefined; let pressedBound: ClientRect | undefined; + let selectedText: string = ""; if (this._iframeRef.current) { const B = this._iframeRef.current.getBoundingClientRect(); const iframeDoc = this._iframeRef.current.contentDocument; if (B && iframeDoc) { // check if there is selected text - const selectedText = iframeDoc.getSelection(); - if (selectedText && selectedText.toString.length > -1) { - - } - console.log("selectedText", selectedText ? selectedText.toString() : ""); - - // TODO: this only works when scale = 1 as it is currently only inteded for mobile upload - const element = iframeDoc.elementFromPoint(this._pressX - B.left, this._pressY - B.top); - console.log("found element", element, element && element.nodeName); - if (element && element.nodeName) {//} === "IMG") { - pressedBound = element.getBoundingClientRect(); - pressedElement = element.cloneNode(true) as HTMLElement; + const text = iframeDoc.getSelection(); + if (text && text.toString().length > 0) { + selectedText = text.toString(); + + // get html of the selected text + const range = text.getRangeAt(0); + const contents = range.cloneContents(); + const div = document.createElement("div"); + div.appendChild(contents); + pressedElement = div; + + pressedBound = range.getBoundingClientRect(); + } else { + // TODO: this only works when scale = 1 as it is currently only inteded for mobile upload + const element = iframeDoc.elementFromPoint(this._pressX - B.left, this._pressY - B.top); + if (element && element.nodeName) {//} === "IMG") { + pressedBound = element.getBoundingClientRect(); + pressedElement = element.cloneNode(true) as HTMLElement; + } } } } // mark the pressed element if (pressedElement && pressedBound) { - console.log("clones b", pressedElement.getBoundingClientRect(), pressedBound); if (this._iframeIndicatorRef.current) { this._iframeIndicatorRef.current.style.top = pressedBound.top + "px"; this._iframeIndicatorRef.current.style.left = pressedBound.left + "px"; @@ -224,13 +232,25 @@ export class WebBox extends DocAnnotatableComponent // start dragging the pressed element if long pressed this._longPressSecondsHack = setTimeout(() => { - if (pressedElement && pressedBound) { + if (selectedText && pressedBound && pressedElement) { + e.stopPropagation(); + e.preventDefault(); + // create doc with the selected text's html + const doc = Docs.Create.HtmlDocument(pressedElement.innerHTML); + + // create dragging ghost with the selected text + if (this._iframeDragRef.current) this._iframeDragRef.current.appendChild(pressedElement); + + // start the drag + const dragData = new DragManager.DocumentDragData([doc]); + DragManager.StartDocumentDrag([pressedElement], dragData, this._pressX - pressedBound.top, this._pressY - pressedBound.top, { hideSource: true }); + } else if (pressedElement && pressedBound) { e.stopPropagation(); e.preventDefault(); if (pressedElement.nodeName === "IMG") { const src = pressedElement.getAttribute("src"); // TODO: may not always work if (src) { - const doc = Docs.Create.ImageDocument(src, { _width: 300 }); + const doc = Docs.Create.ImageDocument(src); ImageUtils.ExtractExif(doc); // add clone to div so that dragging ghost is placed properly diff --git a/src/mobile/MobileInterface.tsx b/src/mobile/MobileInterface.tsx index 83410b99d..0c2ed8156 100644 --- a/src/mobile/MobileInterface.tsx +++ b/src/mobile/MobileInterface.tsx @@ -35,6 +35,9 @@ import GoogleAuthenticationManager from '../client/apis/GoogleAuthenticationMana import { listSpec } from '../new_fields/Schema'; import { Id } from '../new_fields/FieldSymbols'; import { DocumentManager } from '../client/util/DocumentManager'; +import RichTextMenu from '../client/util/RichTextMenu'; +import { WebField } from "../new_fields/URLField"; +import { FieldResult } from "../new_fields/Doc"; library.add(faLongArrowAltLeft); @@ -235,6 +238,20 @@ export default class MobileInterface extends React.Component { e.preventDefault(); } + addWebToCollection = async () => { + let url = "https://en.wikipedia.org/wiki/Hedgehog"; + if (this.mainContainer) { + const data = Cast(this.mainContainer.data, listSpec(Doc)); + if (data) { + const webDoc = await data[0]; + const urlField: FieldResult = Cast(webDoc.data, WebField); + url = urlField ? urlField.url.toString() : "https://en.wikipedia.org/wiki/Hedgehog"; + + } + } + Docs.Create.WebDocument(url, { _width: 300, _height: 300, title: "Mobile Upload Web Doc" }); + } + renderUploadContent() { if (this.mainContainer) { return ( @@ -244,6 +261,7 @@ export default class MobileInterface extends React.Component {
+ {/* */}
@@ -302,6 +320,7 @@ export default class MobileInterface extends React.Component { {/* */} + {/* */} @@ -315,4 +334,5 @@ Scripting.addGlobal(function onSwitchMobileInking() { return MobileInterface.Ins Scripting.addGlobal(function renderMobileInking() { return MobileInterface.Instance.renderInkingContent(); }); Scripting.addGlobal(function onSwitchMobileUpload() { return MobileInterface.Instance.onSwitchUpload(); }); Scripting.addGlobal(function renderMobileUpload() { return MobileInterface.Instance.renderUploadContent(); }); +Scripting.addGlobal(function addWebToMobileUpload() { return MobileInterface.Instance.addWebToCollection(); }); diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 6c916689a..71da0b380 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -155,6 +155,7 @@ export class CurrentUserUtils { } static setupMobileUploadDoc(userDoc: Doc) { + // const addButton = Docs.Create.FontIconDocument({ onDragStart: ScriptField.MakeScript('addWebToMobileUpload()'), title: "Add Web Doc to Upload Collection", icon: "plus", backgroundColor: "black" }) const webDoc = Docs.Create.WebDocument("https://www.britannica.com/animal/cat", { title: "Upload Images From the Web", _chromeStatus: "enabled", lockedPosition: true }); -- cgit v1.2.3-70-g09d2 From 30f42e403bd8cca4d20fc1b0d1cf28fbfa3a1524 Mon Sep 17 00:00:00 2001 From: bob Date: Wed, 12 Feb 2020 14:54:07 -0500 Subject: moved showTitle,etc to use _showTitle,etc --- src/client/documents/Documents.ts | 8 +++++--- src/client/views/DocumentButtonBar.tsx | 2 +- src/client/views/TemplateMenu.tsx | 2 +- src/client/views/collections/CollectionStackingView.tsx | 4 +--- src/client/views/collections/CollectionTreeView.tsx | 4 ++-- src/client/views/nodes/DocumentView.tsx | 14 +++++++------- src/new_fields/documentSchemas.ts | 6 +++--- src/server/authentication/models/current_user_utils.ts | 2 +- 8 files changed, 21 insertions(+), 21 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index cc18dc0a6..ec5116539 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -70,7 +70,9 @@ export interface DocumentOptions { _fitWidth?: boolean; _fitToBox?: boolean; // whether a freeformview should zoom/scale to create a shrinkwrapped view of its contents _LODdisable?: boolean; - dropAction?: dropActionType; + _showTitleHover?: string; // + _showTitle?: string; // which field to display in the title area. leave empty to have no title + _showCaption?: string; // which field to display in the caption area. leave empty to have no caption _chromeStatus?: string; _viewType?: number; _gridGap?: number; // gap between items in masonry view @@ -82,6 +84,7 @@ export interface DocumentOptions { x?: number; y?: number; z?: number; + dropAction?: dropActionType; layoutKey?: string; type?: string; title?: string; @@ -109,7 +112,6 @@ export interface DocumentOptions { documentText?: string; borderRounding?: string; boxShadow?: string; - showTitle?: string; sectionFilter?: string; // field key used to determine headings for sections in stacking and masonry views schemaColumns?: List; dockingConfig?: string; @@ -392,7 +394,7 @@ export namespace Docs { Scripting.addGlobal(Buxton); const delegateKeys = ["x", "y", "layoutKey", "_width", "_height", "_panX", "_panY", "_viewType", "_nativeWidth", "_nativeHeight", "dropAction", "_annotationOn", - "_chromeStatus", "_forceActive", "_autoHeight", "_fitWidth", "_LODdisable", "_itemIndex", "_showSidebar", "showTitle"]; + "_chromeStatus", "_forceActive", "_autoHeight", "_fitWidth", "_LODdisable", "_itemIndex", "_showSidebar", "_showTitle", "_showCaption", "_showTitleHover"]; /** * This function receives the relevant document prototype and uses diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx index ee850922a..ff0d2718c 100644 --- a/src/client/views/DocumentButtonBar.tsx +++ b/src/client/views/DocumentButtonBar.tsx @@ -301,7 +301,7 @@ export class DocumentButtonBar extends React.Component<{ views: (DocumentView | const view0 = this.view0; const templates: Map = new Map(); Array.from(Object.values(Templates.TemplateList)).map(template => - templates.set(template, this.props.views.reduce((checked, doc) => checked || doc?.getLayoutPropStr("show" + template.Name) ? true : false, false as boolean))); + templates.set(template, this.props.views.reduce((checked, doc) => checked || doc?.getLayoutPropStr("_show" + template.Name) ? true : false, false as boolean))); return !view0 ? (null) :
v).map(v => v as DocumentView)} templates={templates} />}> diff --git a/src/client/views/TemplateMenu.tsx b/src/client/views/TemplateMenu.tsx index 64d1e96e1..595c3817e 100644 --- a/src/client/views/TemplateMenu.tsx +++ b/src/client/views/TemplateMenu.tsx @@ -64,7 +64,7 @@ export class TemplateMenu extends React.Component { @undoBatch @action toggleTemplate = (event: React.ChangeEvent, template: Template): void => { - this.props.docViews.forEach(d => Doc.Layout(d.Document)["show" + template.Name] = event.target.checked ? template.Name.toLowerCase() : ""); + this.props.docViews.forEach(d => Doc.Layout(d.Document)["_show" + template.Name] = event.target.checked ? template.Name.toLowerCase() : ""); } @action diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index d21ae32bc..7d1f2c284 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -40,7 +40,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { @computed get sectionFilter() { return StrCast(this.props.Document.sectionFilter); } @computed get filteredChildren() { return this.childLayoutPairs.filter(pair => pair.layout instanceof Doc && !pair.layout.isMinimized).map(pair => pair.layout); } @computed get xMargin() { return NumCast(this.props.Document._xMargin, 2 * Math.min(this.gridGap, .05 * this.props.PanelWidth())); } - @computed get yMargin() { return Math.max(this.props.Document.showTitle && !this.props.Document.showTitleHover ? 30 : 0, NumCast(this.props.Document._yMargin, 0)); } // 2 * this.gridGap)); } + @computed get yMargin() { return Math.max(this.props.Document._showTitle && !this.props.Document._showTitleHover ? 30 : 0, NumCast(this.props.Document._yMargin, 0)); } // 2 * this.gridGap)); } @computed get gridGap() { return NumCast(this.props.Document._gridGap, 10); } @computed get isStackingView() { return BoolCast(this.props.Document.singleColumn, true); } @computed get numGroupColumns() { return this.isStackingView ? Math.max(1, this.Sections.size + (this.showAddAGroup ? 1 : 0)) : 1; } @@ -369,8 +369,6 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { if (!e.isPropagationStopped()) { const subItems: ContextMenuProps[] = []; subItems.push({ description: `${this.props.Document.fillColumn ? "Variable Size" : "Autosize"} Column`, event: () => this.props.Document.fillColumn = !this.props.Document.fillColumn, icon: "plus" }); - subItems.push({ description: `${this.props.Document.showTitles ? "Hide Titles" : "Show Titles"}`, event: () => this.props.Document.showTitles = !this.props.Document.showTitles ? "title" : "", icon: "plus" }); - subItems.push({ description: `${this.props.Document.showCaptions ? "Hide Captions" : "Show Captions"}`, event: () => this.props.Document.showCaptions = !this.props.Document.showCaptions ? "caption" : "", icon: "plus" }); ContextMenu.Instance.addItem({ description: "Stacking Options ...", subitems: subItems, icon: "eye" }); } } diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index be2947dff..e57003f82 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -656,8 +656,8 @@ export class CollectionTreeView extends CollectionSubView(Document) { const heroView = ImageDocument(fallbackImg, { title: "heroView", isTemplateDoc: true, isTemplateForField: "hero", }); // this acts like a template doc and a template field ... a little weird, but seems to work? heroView.proto!.layout = ImageBox.LayoutString("hero"); - heroView.showTitle = "title"; - heroView.showTitleHover = "titlehover"; + heroView._showTitle = "title"; + heroView._showTitleHover = "titlehover"; Doc.AddDocToList(CurrentUserUtils.UserDocument.expandingButtons as Doc, "data", Docs.Create.FontIconDocument({ diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 84a4e2649..48df1ea33 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -232,7 +232,7 @@ export class DocumentView extends DocComponent(Docu e.stopPropagation(); e.preventDefault(); if (e.key === "†" || e.key === "t") { - if (!StrCast(this.layoutDoc.showTitle)) this.layoutDoc.showTitle = "title"; + if (!StrCast(this.layoutDoc._showTitle)) this.layoutDoc._showTitle = "title"; if (!this._titleRef.current) setTimeout(() => this._titleRef.current?.setIsFocused(true), 0); else if (!this._titleRef.current.setIsFocused(true)) { // if focus didn't change, focus on interior text... { @@ -807,16 +807,16 @@ export class DocumentView extends DocComponent(Docu // does Document set a layout prop setsLayoutProp = (prop: string) => this.props.Document[prop] !== this.props.Document["default" + prop[0].toUpperCase() + prop.slice(1)] && this.props.Document["default" + prop[0].toUpperCase() + prop.slice(1)]; // get the a layout prop by first choosing the prop from Document, then falling back to the layout doc otherwise. - getLayoutPropStr = (prop: string) => StrCast(this.setsLayoutProp(prop) ? this.props.Document[prop] : this.layoutDoc[prop]); + getLayoutPropStr = (prop: string) => { + return StrCast(this.setsLayoutProp(prop) ? this.props.Document[prop] : Cast(this.layoutDoc?.expandedTemplate, Doc, null)?.[prop] || this.layoutDoc[prop]); + } getLayoutPropNum = (prop: string) => NumCast(this.setsLayoutProp(prop) ? this.props.Document[prop] : this.layoutDoc[prop]); isSelected = (outsideReaction?: boolean) => SelectionManager.IsSelected(this, outsideReaction); select = (ctrlPressed: boolean) => { SelectionManager.SelectDoc(this, ctrlPressed); }; chromeHeight = () => { - const showTitle = StrCast(this.layoutDoc.showTitle); - const showTitleHover = StrCast(this.layoutDoc.showTitleHover); - return (showTitle && !showTitleHover ? 0 : 0) + 1; + return 1; } @computed get finalLayoutKey() { @@ -874,8 +874,8 @@ export class DocumentView extends DocComponent(Docu @computed get innards() { TraceMobx(); - const showTitle = StrCast(this.getLayoutPropStr("showTitle")); - const showTitleHover = StrCast(this.getLayoutPropStr("showTitleHover")); + const showTitle = StrCast(this.getLayoutPropStr("_showTitle")); + const showTitleHover = StrCast(this.getLayoutPropStr("_showTitleHover")); const showCaption = this.getLayoutPropStr("showCaption"); const showTextTitle = showTitle && (StrCast(this.layoutDoc.layout).indexOf("PresBox") !== -1 || StrCast(this.layoutDoc.layout).indexOf("FormattedTextBox") !== -1) ? showTitle : undefined; const searchHighlight = (!this.Document.searchFields ? (null) : diff --git a/src/new_fields/documentSchemas.ts b/src/new_fields/documentSchemas.ts index 962ef2f4b..81f073855 100644 --- a/src/new_fields/documentSchemas.ts +++ b/src/new_fields/documentSchemas.ts @@ -14,6 +14,9 @@ export const documentSchema = createSchema({ _nativeHeight: "number", // " _width: "number", // width of document in its container's coordinate system _height: "number", // " + _showCaption: "string", // whether editable caption text is overlayed at the bottom of the document + _showTitle: "string", // the fieldkey whose contents should be displayed at the top of the document + _showTitleHover: "string", // the showTitle should be shown only on hover _freeformLayoutEngine: "string",// the string ID for the layout engine to use to layout freeform view documents _LODdisable: "boolean", // whether to disbale LOD switching for CollectionFreeFormViews _pivotField: "string", // specifies which field should be used as the timeline/pivot axis @@ -46,9 +49,6 @@ export const documentSchema = createSchema({ borderRounding: "string", // border radius rounding of document searchFields: "string", // the search fields to display when this document matches a search in its metadata heading: "number", // the logical layout 'heading' of this document (used by rule provider to stylize h1 header elements, from h2, etc) - showCaption: "string", // whether editable caption text is overlayed at the bottom of the document - showTitle: "string", // the fieldkey whose contents should be displayed at the top of the document - showTitleHover: "string", // the showTitle should be shown only on hover isButton: "boolean", // whether document functions as a button (overiding native interactions of its content) ignoreClick: "boolean", // whether documents ignores input clicks (but does not ignore manipulation and other events) scrollToLinkID: "string", // id of link being traversed. allows this doc to scroll/highlight/etc its link anchor. scrollToLinkID should be set to undefined by this doc after it sets up its scroll,etc. diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index ce4f94d83..fde1c9790 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -271,7 +271,7 @@ export class CurrentUserUtils { // the initial presentation Doc to use static setupDefaultPresentation(doc: Doc) { doc.presentationTemplate = new PrefetchProxy(Docs.Create.PresElementBoxDocument({ backgroundColor: "transparent", _xMargin: 5, _height: 46, isTemplateDoc: true, isTemplateForField: "data" })); - doc.curPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, _LODdisable: true, _chromeStatus: "replaced", showTitle: "title", boxShadow: "0 0" }); + doc.curPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, _LODdisable: true, _chromeStatus: "replaced", _showTitle: "title", boxShadow: "0 0" }); } static setupMobileUploads(doc: Doc) { -- cgit v1.2.3-70-g09d2 From 77b0746c5eeed652d6b2bd71d02783ab8d3c0296 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 13 Feb 2020 01:18:03 -0500 Subject: made time controls show only on hover. fixed removing from template collection. fixed errors. --- src/client/views/collections/CollectionTimeView.scss | 7 +++++++ src/client/views/collections/CollectionView.tsx | 2 +- src/new_fields/Doc.ts | 2 -- src/server/authentication/models/current_user_utils.ts | 2 +- 4 files changed, 9 insertions(+), 4 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/views/collections/CollectionTimeView.scss b/src/client/views/collections/CollectionTimeView.scss index 2dffb3ea0..6ea5e6908 100644 --- a/src/client/views/collections/CollectionTimeView.scss +++ b/src/client/views/collections/CollectionTimeView.scss @@ -67,6 +67,7 @@ pointer-events: all; padding: 5px; border: 1px solid black; + display:none; } .collectionTimeView-treeView { @@ -131,4 +132,10 @@ .collectionFreeform-customText { text-align: center; } +} + +.collectionTimeView:hover, .collectionTimeView-pivot:hover { + .pivotKeyEntry { + display:unset; + } } \ No newline at end of file diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index de3e9737f..ad39b69d8 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -145,7 +145,7 @@ export class CollectionView extends Touchable { removeDocument(doc: Doc): boolean { const docView = DocumentManager.Instance.getDocumentView(doc, this.props.ContainingCollectionView); docView && SelectionManager.DeselectDoc(docView); - const targetDataDoc = this.props.Document.resolvedDataDoc ? this.props.Document : this.props.Document[DataSym]; + const targetDataDoc = this.props.Document.resolvedDataDoc && !this.props.Document.isTemplateForField ? this.props.Document : Doc.GetProto(this.props.Document[DataSym]); const value = Cast(targetDataDoc[this.props.fieldKey], listSpec(Doc), []); let index = value.reduce((p, v, i) => (v instanceof Doc && v === doc) ? i : p, -1); index = index !== -1 ? index : value.reduce((p, v, i) => (v instanceof Doc && Doc.AreProtosEqual(v, doc)) ? i : p, -1); diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index 447dbe3b0..2305f2dce 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -858,8 +858,6 @@ export namespace Doc { } } - @undoBatch - @action export function freezeNativeDimensions(layoutDoc: Doc, width: number, height: number): void { layoutDoc._autoHeight = false; layoutDoc.ignoreAspect = false; diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index fde1c9790..45875d455 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -48,7 +48,7 @@ export class CurrentUserUtils { // setup the "creator" buttons for the sidebar-- eg. the default set of draggable document creation tools static setupCreatorButtons(doc: Doc, buttons?: string[]) { const notes = CurrentUserUtils.setupNoteTypes(doc); - const emptyPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, _LODdisable: true, _chromeStatus: "replaced", showTitle: "title", boxShadow: "0 0" }); + const emptyPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, _LODdisable: true, _chromeStatus: "replaced", _showTitle: "title", boxShadow: "0 0" }); const emptyCollection = Docs.Create.FreeformDocument([], { _nativeWidth: undefined, _nativeHeight: undefined, _LODdisable: true, _width: 150, _height: 100, title: "freeform" }); doc.noteTypes = Docs.Create.TreeDocument(notes, { title: "Note Types", _height: 75 }); doc.activePen = doc; -- cgit v1.2.3-70-g09d2 From 553fb2a11aa638c35192a1a2f7da99729867e542 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 13 Feb 2020 22:30:32 -0500 Subject: starting a broad cleanup of code. trying to make standard doc field names be more regular --- src/client/documents/Documents.ts | 15 ++-- src/client/util/DragManager.ts | 1 - src/client/util/RichTextRules.ts | 3 +- src/client/views/MainView.tsx | 7 +- .../views/collections/CollectionCarouselView.scss | 1 + .../views/collections/CollectionCarouselView.tsx | 1 - .../views/collections/CollectionLinearView.tsx | 10 +-- src/client/views/collections/CollectionSubView.tsx | 5 +- .../views/collections/CollectionTreeView.tsx | 35 ++++----- src/client/views/collections/CollectionView.tsx | 5 +- .../collectionFreeForm/CollectionFreeFormView.tsx | 3 +- .../views/nodes/ContentFittingDocumentView.tsx | 24 +----- src/client/views/nodes/DocumentView.tsx | 36 ++------- src/client/views/nodes/FormattedTextBox.tsx | 11 --- src/client/views/nodes/ImageBox.tsx | 9 ++- src/new_fields/Doc.ts | 90 +++++++++------------- src/new_fields/documentSchemas.ts | 12 ++- .../authentication/models/current_user_utils.ts | 8 +- 18 files changed, 96 insertions(+), 180 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 8304c2a7f..adcdf260d 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -22,7 +22,6 @@ import { ImageField, VideoField, AudioField, PdfField, WebField, YoutubeField } import { HtmlField } from "../../new_fields/HtmlField"; import { List } from "../../new_fields/List"; import { Cast, NumCast } from "../../new_fields/Types"; -import { IconField } from "../../new_fields/IconField"; import { listSpec } from "../../new_fields/Schema"; import { DocServer } from "../DocServer"; import { dropActionType } from "../util/DragManager"; @@ -53,7 +52,6 @@ import { InkingStroke } from "../views/InkingStroke"; import { InkField } from "../../new_fields/InkField"; import { InkingControl } from "../views/InkingControl"; import { RichTextField } from "../../new_fields/RichTextField"; -import { Networking } from "../Network"; import { extname } from "path"; import { MessageStore } from "../../server/Message"; const requestImageSize = require('../util/request-image-size'); @@ -92,7 +90,6 @@ export interface DocumentOptions { scale?: number; isDisplayPanel?: boolean; // whether the panel functions as GoldenLayout "stack" used to display documents forceActive?: boolean; - preventTreeViewOpen?: boolean; // ignores the treeViewOpen Doc flag which allows a treeViewItem's expande/collapse state to be independent of other views of the same document in the tree view layout?: string | Doc; hideHeadings?: boolean; // whether stacking view column headings should be hidden isTemplateForField?: string; // the field key for which the containing document is a rendering template @@ -109,7 +106,6 @@ export interface DocumentOptions { curPage?: number; currentTimecode?: number; // the current timecode of a time-based document (e.g., current time of a video) value is in seconds displayTimecode?: number; // the time that a document should be displayed (e.g., time an annotation should be displayed on a video) - documentText?: string; borderRounding?: string; boxShadow?: string; sectionFilter?: string; // field key used to determine headings for sections in stacking and masonry views @@ -124,15 +120,16 @@ export interface DocumentOptions { onChildClick?: ScriptField; // script given to children of a collection to execute when they are clicked onPointerDown?: ScriptField; onPointerUp?: ScriptField; + dropConverter?: ScriptField; // script to run when documents are dropped on this Document. dragFactory?: Doc; // document to create when dragging with a suitable onDragStart script onDragStart?: ScriptField; //script to execute at start of drag operation -- e.g., when a "creator" button is dragged this script generates a different document to drop - clipboard?: Doc; //script to execute at start of drag operation -- e.g., when a "creator" button is dragged this script generates a different document to drop + clipboard?: Doc; icon?: string; sourcePanel?: Doc; // panel to display in 'targetContainer' as the result of a button onClick script targetContainer?: Doc; // document whose proto will be set to 'panel' as the result of a onClick click script - dropConverter?: ScriptField; // script to run when documents are dropped on this Document. strokeWidth?: number; color?: string; + treeViewPreventOpen?: boolean; // ignores the treeViewOpen Doc flag which allows a treeViewItem's expand/collapse state to be independent of other views of the same document in the tree view treeViewHideTitle?: boolean; // whether to hide the title of a tree view treeViewHideHeaderFields?: boolean; // whether to hide the drop down options for tree view items. treeViewOpen?: boolean; // whether this document is expanded in a tree view @@ -141,9 +138,9 @@ export interface DocumentOptions { limitHeight?: number; // maximum height for newly created (eg, from pasting) text documents // [key: string]: Opt; pointerHack?: boolean; // for buttons, allows onClick handler to fire onPointerDown - isExpanded?: boolean; // is linear view expanded - textTransform?: string; // is linear view expanded - letterSpacing?: string; // is linear view expanded + linearViewIsExpanded?: boolean; // is linear view expanded + textTransform?: string; + letterSpacing?: string; } class EmptyBox { diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index e572f0fcb..2877d5fd7 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -134,7 +134,6 @@ export namespace DragManager { embedDoc?: boolean; moveDocument?: MoveFunction; isSelectionMove?: boolean; // indicates that an explicitly selected Document is being dragged. this will suppress onDragStart scripts - applyAsTemplate?: boolean; } export class LinkDragData { constructor(linkSourceDoc: Doc) { diff --git a/src/client/util/RichTextRules.ts b/src/client/util/RichTextRules.ts index 6b8762a5e..de0f46202 100644 --- a/src/client/util/RichTextRules.ts +++ b/src/client/util/RichTextRules.ts @@ -121,8 +121,7 @@ export class RichTextRules { new InputRule( new RegExp(/##$/), (state, match, start, end) => { - const schemaDoc = Doc.GetDataDoc(this.Document); - const textDoc = Doc.GetProto(Cast(schemaDoc[DataSym], Doc, null)!); + const textDoc = this.Document[DataSym]; const numInlines = NumCast(textDoc.inlineTextCount); textDoc.inlineTextCount = numInlines + 1; const inlineFieldKey = "inline" + numInlines; // which field on the text document this annotation will write to diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 401a4b15c..192f3b8fb 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -482,12 +482,13 @@ export class MainView extends React.Component { return new Transform(-translateX, -translateY, 1 / scale); } @computed get docButtons() { - if (CurrentUserUtils.UserDocument?.expandingButtons instanceof Doc) { + const expandingBtns = Doc.UserDoc()?.expandingButtons; + if (expandingBtns instanceof Doc) { return
+ style={{ height: !expandingBtns.linearViewIsExpanded ? "42px" : undefined }} > this.props.Document[HeightSym]() + this.childDocs.length + (this.props.Document.isExpanded ? 1 : 0), - () => this.props.Document._width = 5 + (this.props.Document.isExpanded ? this.childDocs.length * (this.props.Document[HeightSym]()) : 10), + this._widthDisposer = reaction(() => this.props.Document[HeightSym]() + this.childDocs.length + (this.props.Document.linearViewIsExpanded ? 1 : 0), + () => this.props.Document._width = 5 + (this.props.Document.linearViewIsExpanded ? this.childDocs.length * (this.props.Document[HeightSym]()) : 10), { fireImmediately: true } ); @@ -84,8 +84,8 @@ export class CollectionLinearView extends CollectionSubView(LinearDocument) { const guid = Utils.GenerateGuid(); return
- this.props.Document.isExpanded = this.addMenuToggle.current!.checked)} /> + this.props.Document.linearViewIsExpanded = this.addMenuToggle.current!.checked)} />
@@ -97,7 +97,7 @@ export class CollectionLinearView extends CollectionSubView(LinearDocument) { return
(schemaCtor: (doc: Doc) => T) { const docDragData = de.complete.docDragData; (this.props.Document.dropConverter instanceof ScriptField) && this.props.Document.dropConverter.script.run({ dragData: docDragData }); /// bcz: check this - if (docDragData && !docDragData.applyAsTemplate) { + if (docDragData) { if (de.altKey && docDragData.draggedDocuments.length) { this.childDocs.map(doc => { doc.layout_fromParent = docDragData.draggedDocuments[0]; @@ -253,7 +253,8 @@ export function CollectionSubView(schemaCtor: (doc: Doc) => T) { } }); } else { - const htmlDoc = Docs.Create.HtmlDocument(html, { ...options, title: "-web page-", _width: 300, _height: 300, documentText: text }); + const htmlDoc = Docs.Create.HtmlDocument(html, { ...options, title: "-web page-", _width: 300, _height: 300 }); + Doc.GetProto(htmlDoc)["data-text"] = text; this.props.addDocument(htmlDoc); } return; diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index e91c3cc49..a160dcc62 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -61,7 +61,7 @@ export interface TreeViewProps { parentKey: string; active: (outsideReaction?: boolean) => boolean; treeViewHideHeaderFields: () => boolean; - preventTreeViewOpen: boolean; + treeViewPreventOpen: boolean; renderedIds: string[]; onCheckedClick?: ScriptField; } @@ -84,7 +84,7 @@ library.add(faPlus, faMinus); * * special fields: * treeViewOpen : flag denoting whether the documents sub-tree (contents) is visible or hidden - * preventTreeViewOpen : ignores the treeViewOpen flag (for allowing a view to not be slaved to other views of the document) + * treeViewPreventOpen : ignores the treeViewOpen flag (for allowing a view to not be slaved to other views of the document) * treeViewExpandedView : name of field whose contents are being displayed as the document's subtree */ class TreeView extends React.Component { @@ -96,8 +96,8 @@ class TreeView extends React.Component { get defaultExpandedView() { return this.childDocs ? this.fieldKey : StrCast(this.props.document.defaultExpandedView, "fields"); } @observable _overrideTreeViewOpen = false; // override of the treeViewOpen field allowing the display state to be independent of the document's state - set treeViewOpen(c: boolean) { if (this.props.preventTreeViewOpen) this._overrideTreeViewOpen = c; else this.props.document.treeViewOpen = this._overrideTreeViewOpen = c; } - @computed get treeViewOpen() { return (!this.props.preventTreeViewOpen && BoolCast(this.props.document.treeViewOpen)) || this._overrideTreeViewOpen; } + set treeViewOpen(c: boolean) { if (this.props.treeViewPreventOpen) this._overrideTreeViewOpen = c; else this.props.document.treeViewOpen = this._overrideTreeViewOpen = c; } + @computed get treeViewOpen() { return (!this.props.treeViewPreventOpen && BoolCast(this.props.document.treeViewOpen)) || this._overrideTreeViewOpen; } @computed get treeViewExpandedView() { return StrCast(this.props.document.treeViewExpandedView, this.defaultExpandedView); } @computed get MAX_EMBED_HEIGHT() { return NumCast(this.props.document.maxEmbedHeight, 300); } @computed get dataDoc() { return this.templateDataDoc ? this.templateDataDoc : this.props.document; } @@ -179,8 +179,7 @@ class TreeView extends React.Component { SetValue={undoBatch((value: string) => Doc.SetInPlace(this.props.document, key, value, false) || true)} OnFillDown={undoBatch((value: string) => { Doc.SetInPlace(this.props.document, key, value, false); - const layoutDoc = this.props.document.layout_custom instanceof Doc ? Doc.ApplyTemplate(Doc.GetProto(this.props.document.layout_custom)) : undefined; - const doc = layoutDoc || Docs.Create.FreeformDocument([], { title: "", x: 0, y: 0, _width: 100, _height: 25, templates: new List([Templates.Title.Layout]) }); + const doc = Docs.Create.FreeformDocument([], { title: "", x: 0, y: 0, _width: 100, _height: 25, templates: new List([Templates.Title.Layout]) }); EditableView.loadId = doc[Id]; return this.props.addDocument(doc); })} @@ -291,7 +290,7 @@ class TreeView extends React.Component { contentElement = TreeView.GetChildElements(contents instanceof Doc ? [contents] : DocListCast(contents), this.props.treeViewId, doc, undefined, key, this.props.containingCollection, this.props.prevSibling, addDoc, remDoc, this.move, this.props.dropAction, this.props.addDocTab, this.props.pinToPres, this.props.ScreenToLocalTransform, this.props.outerXf, this.props.active, - this.props.panelWidth, this.props.ChromeHeight, this.props.renderDepth, this.props.treeViewHideHeaderFields, this.props.preventTreeViewOpen, + this.props.panelWidth, this.props.ChromeHeight, this.props.renderDepth, this.props.treeViewHideHeaderFields, this.props.treeViewPreventOpen, [...this.props.renderedIds, doc[Id]], this.props.libraryPath, this.props.onCheckedClick); } else { contentElement = { TreeView.GetChildElements(docs, this.props.treeViewId, Doc.Layout(this.props.document), this.templateDataDoc, expandKey, this.props.containingCollection, this.props.prevSibling, addDoc, remDoc, this.move, this.props.dropAction, this.props.addDocTab, this.props.pinToPres, this.props.ScreenToLocalTransform, - this.props.outerXf, this.props.active, this.props.panelWidth, this.props.ChromeHeight, this.props.renderDepth, this.props.treeViewHideHeaderFields, this.props.preventTreeViewOpen, + this.props.outerXf, this.props.active, this.props.panelWidth, this.props.ChromeHeight, this.props.renderDepth, this.props.treeViewHideHeaderFields, this.props.treeViewPreventOpen, [...this.props.renderedIds, this.props.document[Id]], this.props.libraryPath, this.props.onCheckedClick)} ; } else if (this.treeViewExpandedView === "fields") { @@ -464,7 +463,7 @@ class TreeView extends React.Component { ChromeHeight: undefined | (() => number), renderDepth: number, treeViewHideHeaderFields: () => boolean, - preventTreeViewOpen: boolean, + treeViewPreventOpen: boolean, renderedIds: string[], libraryPath: Doc[] | undefined, onCheckedClick: ScriptField | undefined @@ -574,7 +573,7 @@ class TreeView extends React.Component { parentKey={key} active={active} treeViewHideHeaderFields={treeViewHideHeaderFields} - preventTreeViewOpen={preventTreeViewOpen} + treeViewPreventOpen={treeViewPreventOpen} renderedIds={renderedIds} />; }); } @@ -601,8 +600,7 @@ export class CollectionTreeView extends CollectionSubView(Document) { @action remove = (document: Document): boolean => { - const targetDataDoc = this.props.Document && !this.props.Document.isTemplateForField ? this.props.Document : Doc.GetProto(this.props.Document[DataSym] as Doc); - const children = Cast(targetDataDoc[this.props.fieldKey], listSpec(Doc), []); + const children = Cast(this.props.Document[DataSym][this.props.fieldKey], listSpec(Doc), []); if (children.indexOf(document) !== -1) { children.splice(children.indexOf(document), 1); return true; @@ -611,10 +609,8 @@ export class CollectionTreeView extends CollectionSubView(Document) { } @action addDoc = (doc: Document, relativeTo: Opt, before?: boolean): boolean => { - const doAddDoc = () => { - const targetDataDoc = this.props.Document && !this.props.Document.isTemplateForField ? this.props.Document : Doc.GetProto(this.props.Document[DataSym] as Doc); - Doc.AddDocToList(targetDataDoc, this.props.fieldKey, doc, relativeTo, before, false, false, false); - }; + const doAddDoc = () => + Doc.AddDocToList(this.props.Document[DataSym], this.props.fieldKey, doc, relativeTo, before, false, false, false); if (this.props.Document.resolvedDataDoc instanceof Promise) { this.props.Document.resolvedDataDoc.then(resolved => doAddDoc()); } else { @@ -637,7 +633,7 @@ export class CollectionTreeView extends CollectionSubView(Document) { ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15); } else { const layoutItems: ContextMenuProps[] = []; - layoutItems.push({ description: (this.props.Document.preventTreeViewOpen ? "Persist" : "Abandon") + "Treeview State", event: () => this.props.Document.preventTreeViewOpen = !this.props.Document.preventTreeViewOpen, icon: "paint-brush" }); + layoutItems.push({ description: (this.props.Document.treeViewPreventOpen ? "Persist" : "Abandon") + "Treeview State", event: () => this.props.Document.treeViewPreventOpen = !this.props.Document.treeViewPreventOpen, icon: "paint-brush" }); layoutItems.push({ description: (this.props.Document.treeViewHideHeaderFields ? "Show" : "Hide") + " Header Fields", event: () => this.props.Document.treeViewHideHeaderFields = !this.props.Document.treeViewHideHeaderFields, icon: "paint-brush" }); layoutItems.push({ description: (this.props.Document.treeViewHideTitle ? "Show" : "Hide") + " Title", event: () => this.props.Document.treeViewHideTitle = !this.props.Document.treeViewHideTitle, icon: "paint-brush" }); ContextMenu.Instance.addItem({ description: "Treeview Options ...", subitems: layoutItems, icon: "eye" }); @@ -733,8 +729,7 @@ export class CollectionTreeView extends CollectionSubView(Document) { SetValue={undoBatch((value: string) => Doc.SetInPlace(this.dataDoc, "title", value, false) || true)} OnFillDown={undoBatch((value: string) => { Doc.SetInPlace(this.dataDoc, "title", value, false); - const layoutDoc = this.props.Document.layout_custom instanceof Doc ? Doc.ApplyTemplate(Doc.GetProto(this.props.Document.layout_custom)) : undefined; - const doc = layoutDoc || Docs.Create.FreeformDocument([], { title: "", x: 0, y: 0, _width: 100, _height: 25, templates: new List([Templates.Title.Layout]) }); + const doc = Docs.Create.FreeformDocument([], { title: "", x: 0, y: 0, _width: 100, _height: 25, templates: new List([Templates.Title.Layout]) }); EditableView.loadId = doc[Id]; this.addDoc(doc, this.childDocs.length ? this.childDocs[0] : undefined, true); })} />)} @@ -744,7 +739,7 @@ export class CollectionTreeView extends CollectionSubView(Document) { TreeView.GetChildElements(this.childDocs, this.props.Document, this.props.Document, this.props.DataDoc, this.props.fieldKey, this.props.ContainingCollectionDoc, undefined, addDoc, this.remove, moveDoc, dropAction, this.props.addDocTab, this.props.pinToPres, this.props.ScreenToLocalTransform, this.outerXf, this.props.active, this.props.PanelWidth, this.props.ChromeHeight, this.props.renderDepth, () => BoolCast(this.props.Document.treeViewHideHeaderFields), - BoolCast(this.props.Document.preventTreeViewOpen), [], this.props.LibraryPath, ScriptCast(this.props.Document.onCheckedClick)) + BoolCast(this.props.Document.treeViewPreventOpen), [], this.props.LibraryPath, ScriptCast(this.props.Document.onCheckedClick)) }
diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index ad39b69d8..39ce4d6e8 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -133,7 +133,7 @@ export class CollectionView extends Touchable { @action.bound addDocument(doc: Doc): boolean { - const targetDataDoc = this.props.Document.resolvedDataDoc && !this.props.Document.isTemplateForField ? this.props.Document : Doc.GetProto(this.props.Document[DataSym]); + const targetDataDoc = this.props.Document[DataSym]; targetDataDoc[this.props.fieldKey] = new List([...DocListCast(targetDataDoc[this.props.fieldKey]), doc]); // DocAddToList may write to targetdataDoc's parent ... we don't want this. should really change GetProto to GetDataDoc and test for resolvedDataDoc there // Doc.AddDocToList(targetDataDoc, this.props.fieldKey, doc); targetDataDoc[this.props.fieldKey + "-lastModified"] = new DateField(new Date(Date.now())); @@ -145,8 +145,7 @@ export class CollectionView extends Touchable { removeDocument(doc: Doc): boolean { const docView = DocumentManager.Instance.getDocumentView(doc, this.props.ContainingCollectionView); docView && SelectionManager.DeselectDoc(docView); - const targetDataDoc = this.props.Document.resolvedDataDoc && !this.props.Document.isTemplateForField ? this.props.Document : Doc.GetProto(this.props.Document[DataSym]); - const value = Cast(targetDataDoc[this.props.fieldKey], listSpec(Doc), []); + const value = Cast(this.props.Document[DataSym][this.props.fieldKey], listSpec(Doc), []); let index = value.reduce((p, v, i) => (v instanceof Doc && v === doc) ? i : p, -1); index = index !== -1 ? index : value.reduce((p, v, i) => (v instanceof Doc && Doc.AreProtosEqual(v, doc)) ? i : p, -1); diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 7f1817a15..e1854fc2d 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -1074,7 +1074,6 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { // this.Document.fitH = this.contentBounds && (this.contentBounds.b - this.contentBounds.y); // if isAnnotationOverlay is set, then children will be stored in the extension document for the fieldKey. // otherwise, they are stored in fieldKey. All annotations to this document are stored in the extension document - // let lodarea = this.Document[WidthSym]() * this.Document[HeightSym]() / this.props.ScreenToLocalTransform().Scale / this.props.ScreenToLocalTransform().Scale; return
- {!this.Document._LODdisable && !this.props.active() && !this.props.isAnnotationOverlay && !this.props.annotationsKey && this.props.renderDepth > 0 ? // && this.props.CollectionView && lodarea < NumCast(this.Document.LODarea, 100000) ? + {!this.Document._LODdisable && !this.props.active() && !this.props.isAnnotationOverlay && !this.props.annotationsKey && this.props.renderDepth > 0 ? this.placeholder : this.marqueeView}
; diff --git a/src/client/views/nodes/ContentFittingDocumentView.tsx b/src/client/views/nodes/ContentFittingDocumentView.tsx index 671f5b96e..5c449026e 100644 --- a/src/client/views/nodes/ContentFittingDocumentView.tsx +++ b/src/client/views/nodes/ContentFittingDocumentView.tsx @@ -1,19 +1,17 @@ import React = require("react"); -import { action, computed } from "mobx"; +import { computed } from "mobx"; import { observer } from "mobx-react"; import "react-table/react-table.css"; import { Doc, Opt } from "../../../new_fields/Doc"; -import { ComputedField, ScriptField } from "../../../new_fields/ScriptField"; +import { ScriptField } from "../../../new_fields/ScriptField"; import { NumCast, StrCast } from "../../../new_fields/Types"; +import { TraceMobx } from "../../../new_fields/util"; import { emptyFunction, returnEmptyString, returnOne } from "../../../Utils"; -import { DragManager } from "../../util/DragManager"; import { Transform } from "../../util/Transform"; -import { undoBatch } from "../../util/UndoManager"; +import { CollectionView } from "../collections/CollectionView"; import '../DocumentDecorations.scss'; import { DocumentView } from "../nodes/DocumentView"; import "./ContentFittingDocumentView.scss"; -import { CollectionView } from "../collections/CollectionView"; -import { TraceMobx } from "../../../new_fields/util"; interface ContentFittingDocumentViewProps { Document?: Doc; @@ -55,20 +53,6 @@ export class ContentFittingDocumentView extends React.Component this.scaling; - @undoBatch - @action - drop = (e: Event, de: DragManager.DropEvent) => { - const docDragData = de.complete.docDragData; - if (docDragData) { - this.props.childDocs && this.props.childDocs.map(otherdoc => { - const target = Doc.GetProto(otherdoc); - target.layout = ComputedField.MakeFunction("this.image_data[0]"); - target.layout_custom = Doc.MakeDelegate(docDragData.draggedDocuments[0]); - }); - e.stopPropagation(); - } - return true; - } private PanelWidth = () => this.panelWidth; private PanelHeight = () => this.panelHeight;; diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 48df1ea33..e9b4f9f7f 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -92,7 +92,6 @@ export class DocumentView extends DocComponent(Docu private _downY: number = 0; private _lastTap: number = 0; private _doubleTap = false; - private _hitTemplateDrag = false; private _mainCont = React.createRef(); private _dropDisposer?: DragManager.DragDropDisposer; private _gestureEventDisposer?: GestureUtils.GestureEventDisposer; @@ -196,14 +195,13 @@ export class DocumentView extends DocComponent(Docu !this.props.dontRegisterView && DocumentManager.Instance.DocumentViews.splice(DocumentManager.Instance.DocumentViews.indexOf(this), 1); } - startDragging(x: number, y: number, dropAction: dropActionType, applyAsTemplate?: boolean) { + startDragging(x: number, y: number, dropAction: dropActionType) { if (this._mainCont.current) { const dragData = new DragManager.DocumentDragData([this.props.Document]); const [left, top] = this.props.ScreenToLocalTransform().scale(this.props.ContentScaling()).inverse().transformPoint(0, 0); dragData.offset = this.props.ScreenToLocalTransform().scale(this.props.ContentScaling()).transformDirection(x - left, y - top); dragData.dropAction = dropAction; dragData.moveDocument = this.props.moveDocument;// this.Document.onDragStart ? undefined : this.props.moveDocument; - dragData.applyAsTemplate = applyAsTemplate; dragData.dragDivName = this.props.dragDivName; this.props.Document.sourceContext = this.props.ContainingCollectionDoc; // bcz: !! shouldn't need this ... use search find the document's context dynamically DragManager.StartDocumentDrag([this._mainCont.current], dragData, x, y, { hideSource: !dropAction && !this.Document.onDragStart }); @@ -257,8 +255,8 @@ export class DocumentView extends DocComponent(Docu let preventDefault = true; if (this._doubleTap && this.props.renderDepth && !this.onClickHandler?.script) { // disable double-click to show full screen for things that have an on click behavior since clicking them twice can be misinterpreted as a double click const fullScreenAlias = Doc.MakeAlias(this.props.Document); - if (StrCast(fullScreenAlias.layoutKey) !== "layout_custom" && fullScreenAlias.layout_custom !== undefined) { - fullScreenAlias.layoutKey = "layout_custom"; + if (StrCast(fullScreenAlias.layoutKey) !== "layout_fullScreen" && fullScreenAlias.layout_fullScreen) { + fullScreenAlias.layoutKey = "layout_fullScreen"; } this.props.addDocTab(fullScreenAlias, undefined, "inTab"); SelectionManager.DeselectAll(); @@ -323,7 +321,7 @@ export class DocumentView extends DocComponent(Docu if (Math.abs(this._downX - touch.clientX) > 3 || Math.abs(this._downY - touch.clientY) > 3) { if (!e.altKey && (!this.topMost || this.Document.onDragStart || this.Document.onClick)) { this.cleanUpInteractions(); - this.startDragging(this._downX, this._downY, this.Document.dropAction ? this.Document.dropAction as any : e.ctrlKey || e.altKey ? "alias" : undefined, this._hitTemplateDrag); + this.startDragging(this._downX, this._downY, this.Document.dropAction ? this.Document.dropAction as any : 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 @@ -434,14 +432,6 @@ export class DocumentView extends DocComponent(Docu if (!e.nativeEvent.cancelBubble || this.onClickHandler || this.Document.onDragStart) { this._downX = e.clientX; this._downY = e.clientY; - this._hitTemplateDrag = false; - // this whole section needs to move somewhere else. We're trying to initiate a special "template" drag where - // this document is the template and we apply it to whatever we drop it on. - for (let element = (e.target as any); element && !this._hitTemplateDrag; element = element.parentElement) { - if (element.className && element.className.toString() === "collectionViewBaseChrome-collapse") { - this._hitTemplateDrag = true; - } - } if ((this.active || this.Document.onDragStart || this.onClickHandler) && !e.ctrlKey && (e.button === 0 || InteractionUtils.IsType(e, InteractionUtils.TOUCHTYPE)) && @@ -470,7 +460,7 @@ export class DocumentView extends DocComponent(Docu if (!e.altKey && (!this.topMost || this.Document.onDragStart || this.onClickHandler) && (e.buttons === 1 || InteractionUtils.IsType(e, InteractionUtils.TOUCHTYPE))) { document.removeEventListener("pointermove", this.onPointerMove); document.removeEventListener("pointerup", this.onPointerUp); - this.startDragging(this._downX, this._downY, this.props.ContainingCollectionDoc?.childDropAction ? this.props.ContainingCollectionDoc?.childDropAction : this.Document.dropAction ? this.Document.dropAction as any : e.ctrlKey || e.altKey ? "alias" : undefined, this._hitTemplateDrag); + this.startDragging(this._downX, this._downY, this.props.ContainingCollectionDoc?.childDropAction ? this.props.ContainingCollectionDoc?.childDropAction : this.Document.dropAction ? this.Document.dropAction as any : 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 @@ -556,17 +546,6 @@ export class DocumentView extends DocComponent(Docu } } - @undoBatch - makeSelBtnClicked = (): void => { - if (this.Document.isButton || this.Document.onClick || this.Document.ignoreClick) { - this.Document.isButton = false; - this.Document.ignoreClick = false; - this.Document.onClick = undefined; - } else { - this.props.Document.isButton = "Selector"; - } - } - @undoBatch @action drop = async (e: Event, de: DragManager.DropEvent) => { @@ -578,10 +557,6 @@ export class DocumentView extends DocComponent(Docu DocUtils.MakeLink({ doc: de.complete.annoDragData.annotationDocument }, { doc: this.props.Document, ctx: this.props.ContainingCollectionDoc }, `Link from ${StrCast(de.complete.annoDragData.annotationDocument.title)}`); } - if (de.complete.docDragData && de.complete.docDragData.applyAsTemplate) { - Doc.ApplyTemplateTo(de.complete.docDragData.draggedDocuments[0], this.props.Document, "layout_custom", undefined); - e.stopPropagation(); - } if (de.complete.linkDragData) { e.stopPropagation(); // const docs = await SearchUtil.Search(`data_l:"${destDoc[Id]}"`, true); @@ -697,7 +672,6 @@ export class DocumentView extends DocComponent(Docu onClicks.push({ description: "Toggle Detail", event: () => this.Document.onClick = ScriptField.MakeScript(`toggleDetail(this, "${this.props.Document.layoutKey}")`), icon: "window-restore" }); onClicks.push({ description: this.Document.ignoreClick ? "Select" : "Do Nothing", event: () => this.Document.ignoreClick = !this.Document.ignoreClick, icon: this.Document.ignoreClick ? "unlock" : "lock" }); onClicks.push({ description: this.Document.isButton || this.Document.onClick ? "Remove Click Behavior" : "Follow Link", event: this.makeBtnClicked, icon: "concierge-bell" }); - onClicks.push({ description: this.props.Document.isButton ? "Remove Select Link Behavior" : "Select Link", event: this.makeSelBtnClicked, icon: "concierge-bell" }); onClicks.push({ description: "Edit onClick Script", icon: "edit", event: (obj: any) => ScriptBox.EditButtonScript("On Button Clicked ...", this.props.Document, "onClick", obj.x, obj.y) }); !existingOnClick && cm.addItem({ description: "OnClick...", subitems: onClicks, icon: "hand-point-right" }); diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 7fbee8881..2fb61f9db 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -250,17 +250,6 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & Doc.GetProto(this.dataDoc)[this.props.fieldKey] = new RichTextField(draggedDoc.data.Data, draggedDoc.data.Text); e.stopPropagation(); } - // apply as template when dragging with Meta - } else if (draggedDoc && draggedDoc.type === DocumentType.TEXT && !Doc.AreProtosEqual(draggedDoc, this.props.Document) && de.metaKey) { - draggedDoc.isTemplateDoc = true; - let newLayout = Doc.Layout(draggedDoc); - if (typeof (draggedDoc.layout) === "string") { - newLayout = Doc.MakeDelegate(draggedDoc); - newLayout.layout = StrCast(newLayout.layout).replace(/fieldKey={'[^']*'}/, `fieldKey={'${this.props.fieldKey}'}`); - } - this.Document.layout_custom = newLayout; - this.Document.layoutKey = "layout_custom"; - e.stopPropagation(); // embed document when dragging with a userDropAction or an embedDoc flag set } else if (de.complete.docDragData.userDropAction || de.complete.docDragData.embedDoc) { const target = de.complete.docDragData.droppedDocuments[0]; diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index c0e102195..364bce7a8 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -92,10 +92,11 @@ export class ImageBox extends DocAnnotatableComponent Cast(target[SelfProxy].proto, Doc) || null, // TODO this might be able to replace the proto logic in getter has: (target, key) => key in target.__fields, - ownKeys: target => Object.keys(target.__allfields), + ownKeys: target => { + let obj = {} as any; + Object.assign(obj, target.___fields); + runInAction(() => obj.__LAYOUT__ = target.__LAYOUT__); + return Object.keys(obj) + }, getOwnPropertyDescriptor: (target, prop) => { if (prop.toString() === "__LAYOUT__") { return Reflect.getOwnPropertyDescriptor(target, prop); @@ -140,17 +144,7 @@ export class Doc extends RefField { [key: string]: FieldResult; @serializable(alias("fields", map(autoObject(), { afterDeserialize: afterDocDeserialize }))) - private get __fields() { - return this.___fields; - } - private get __allfields() { - let obj = {} as any; - Object.assign(obj, this.___fields); - runInAction(() => obj.__LAYOUT__ = this.__LAYOUT__); - return obj; - } - - + private get __fields() { return this.___fields; } private set __fields(value) { this.___fields = value; for (const key in value) { @@ -168,18 +162,19 @@ export class Doc extends RefField { private [UpdatingFromServer]: boolean = false; private [Update] = (diff: any) => { - if (this[UpdatingFromServer]) { - return; - } - DocServer.UpdateField(this[Id], diff); + !this[UpdatingFromServer] && DocServer.UpdateField(this[Id], diff); } private [Self] = this; private [SelfProxy]: any; public [WidthSym] = () => NumCast(this[SelfProxy]._width); public [HeightSym] = () => NumCast(this[SelfProxy]._height); - public get [DataSym]() { return Cast(Doc.Layout(this[SelfProxy]).resolvedDataDoc, Doc, null) || this[SelfProxy]; } public get [LayoutSym]() { return this[SelfProxy].__LAYOUT__; } + public get [DataSym]() { + const self = this[SelfProxy]; + return self.resolvedDataDoc && !self.isTemplateForField ? self : + Doc.GetProto(Cast(Doc.Layout(self).resolvedDataDoc, Doc, null) || self); + } @computed get __LAYOUT__() { const templateLayoutDoc = Cast(Doc.LayoutField(this[SelfProxy]), Doc, null); if (templateLayoutDoc) { @@ -195,12 +190,8 @@ export class Doc extends RefField { return undefined; } - [ToScriptString]() { - return "invalid"; - } - [ToString]() { - return "Doc"; - } + [ToScriptString]() { return "invalid"; } + [ToString]() { return "Doc"; } private [CachedUpdates]: { [key: string]: () => void | Promise } = {}; public static CurrentUserEmail: string = ""; @@ -287,8 +278,7 @@ export namespace Doc { export function Get(doc: Doc, key: string, ignoreProto: boolean = false): FieldResult { try { - const self = doc[Self]; - return getField(self, key, ignoreProto); + return getField(doc[Self], key, ignoreProto); } catch { return doc; } @@ -357,13 +347,12 @@ export namespace Doc { return r || r2 || r3 || r4; } - // gets the document's prototype or returns the document if it is a prototype - export function GetProto(doc: Doc) { - return doc && (Doc.GetT(doc, "isPrototype", "boolean", true) ? doc : (doc.proto || doc)); - } - export function GetDataDoc(doc: Doc): Doc { - const proto = Doc.GetProto(doc); - return proto === doc ? proto : Doc.GetDataDoc(proto); + // Gets the data document for the document. Note: this is mis-named -- it does not specifically + // return the doc's proto, but rather recursively searches through the proto inheritance chain + // and returns the document who's proto is undefined or whose proto is marked as a base prototype ('isPrototype'). + export function GetProto(doc: Doc): Doc { + const proto = doc && (Doc.GetT(doc, "isPrototype", "boolean", true) ? doc : (doc.proto || doc)); + return proto === doc ? proto : Doc.GetProto(proto); } export function allKeys(doc: Doc): string[] { @@ -443,11 +432,6 @@ export namespace Doc { return bounds; } - export function MakeTitled(title: string) { - const doc = new Doc(); - doc.title = title; - return doc; - } export function MakeAlias(doc: Doc, id?: string) { const alias = !GetT(doc, "isPrototype", "boolean", true) ? Doc.MakeCopy(doc, undefined, id) : Doc.MakeDelegate(doc, id); const layout = Doc.LayoutField(alias); @@ -488,7 +472,7 @@ export namespace Doc { if (templateLayoutDoc.resolvedDataDoc instanceof Promise) { expandedTemplateLayout = undefined; - } else if (templateLayoutDoc.resolvedDataDoc === Doc.GetDataDoc(targetDoc)) { + } else if (templateLayoutDoc.resolvedDataDoc === Doc.GetProto(targetDoc)) { expandedTemplateLayout = templateLayoutDoc; } else if (expandedTemplateLayout === undefined) { setTimeout(action(() => { @@ -497,7 +481,7 @@ export namespace Doc { newLayoutDoc.lockedPosition = true; newLayoutDoc.expandedTemplate = targetDoc; targetDoc[expandedLayoutFieldKey] = newLayoutDoc; - const dataDoc = Doc.GetDataDoc(targetDoc); + const dataDoc = Doc.GetProto(targetDoc); newLayoutDoc.resolvedDataDoc = dataDoc; if (dataDoc[templateField] === undefined && templateLayoutDoc[templateField] instanceof List && Cast(templateLayoutDoc[templateField], listSpec(Doc), []).length) { dataDoc[templateField] = ComputedField.MakeFunction(`ObjectField.MakeCopy(templateLayoutDoc["${templateField}"] as List)`, { templateLayoutDoc: Doc.name }, { templateLayoutDoc: templateLayoutDoc }); @@ -660,10 +644,6 @@ export namespace Doc { // assign the template field doc a delegate of any extension document that was previously used to render the template field (since extension doc's carry rendering informatino) Doc.Layout(templateField)[metadataFieldKey + "_ext"] = Doc.MakeDelegate(templateField[templateFieldLayoutString?.split("'")[1] + "_ext"] as Doc); - if (templateField.backgroundColor !== templateDoc?.defaultBackgroundColor) { - templateField.defaultBackgroundColor = templateField.backgroundColor; - } - return true; } @@ -716,26 +696,26 @@ export namespace Doc { export function SetUserDoc(doc: Doc) { manager._user_doc = doc; } export function IsBrushed(doc: Doc) { return computedFn(function IsBrushed(doc: Doc) { - return brushManager.BrushedDoc.has(doc) || brushManager.BrushedDoc.has(Doc.GetDataDoc(doc)); + return brushManager.BrushedDoc.has(doc) || brushManager.BrushedDoc.has(Doc.GetProto(doc)); })(doc); } // don't bother memoizing (caching) the result if called from a non-reactive context. (plus this avoids a warning message) export function IsBrushedDegreeUnmemoized(doc: Doc) { - return brushManager.BrushedDoc.has(doc) ? 2 : brushManager.BrushedDoc.has(Doc.GetDataDoc(doc)) ? 1 : 0; + return brushManager.BrushedDoc.has(doc) ? 2 : brushManager.BrushedDoc.has(Doc.GetProto(doc)) ? 1 : 0; } export function IsBrushedDegree(doc: Doc) { return computedFn(function IsBrushDegree(doc: Doc) { - return brushManager.BrushedDoc.has(doc) ? 2 : brushManager.BrushedDoc.has(Doc.GetDataDoc(doc)) ? 1 : 0; + return Doc.IsBrushedDegreeUnmemoized(doc); })(doc); } export function BrushDoc(doc: Doc) { brushManager.BrushedDoc.set(doc, true); - brushManager.BrushedDoc.set(Doc.GetDataDoc(doc), true); + brushManager.BrushedDoc.set(Doc.GetProto(doc), true); return doc; } export function UnBrushDoc(doc: Doc) { brushManager.BrushedDoc.delete(doc); - brushManager.BrushedDoc.delete(Doc.GetDataDoc(doc)); + brushManager.BrushedDoc.delete(Doc.GetProto(doc)); return doc; } @@ -748,14 +728,14 @@ export namespace Doc { document.removeEventListener("pointerdown", linkFollowUnhighlight); } - let dt = 0; + let _lastDate = 0; export function linkFollowHighlight(destDoc: Doc, dataAndDisplayDocs = true) { linkFollowUnhighlight(); Doc.HighlightDoc(destDoc, dataAndDisplayDocs); document.removeEventListener("pointerdown", linkFollowUnhighlight); document.addEventListener("pointerdown", linkFollowUnhighlight); - const x = dt = Date.now(); - window.setTimeout(() => dt === x && linkFollowUnhighlight(), 5000); + const lastDate = _lastDate = Date.now(); + window.setTimeout(() => _lastDate === lastDate && linkFollowUnhighlight(), 5000); } export class HighlightBrush { @@ -763,18 +743,18 @@ export namespace Doc { } const highlightManager = new HighlightBrush(); export function IsHighlighted(doc: Doc) { - return highlightManager.HighlightedDoc.get(doc) || highlightManager.HighlightedDoc.get(Doc.GetDataDoc(doc)); + return highlightManager.HighlightedDoc.get(doc) || highlightManager.HighlightedDoc.get(Doc.GetProto(doc)); } export function HighlightDoc(doc: Doc, dataAndDisplayDocs = true) { runInAction(() => { highlightManager.HighlightedDoc.set(doc, true); - dataAndDisplayDocs && highlightManager.HighlightedDoc.set(Doc.GetDataDoc(doc), true); + dataAndDisplayDocs && highlightManager.HighlightedDoc.set(Doc.GetProto(doc), true); }); } export function UnHighlightDoc(doc: Doc) { runInAction(() => { highlightManager.HighlightedDoc.set(doc, false); - highlightManager.HighlightedDoc.set(Doc.GetDataDoc(doc), false); + highlightManager.HighlightedDoc.set(Doc.GetProto(doc), false); }); } export function UnhighlightAll() { diff --git a/src/new_fields/documentSchemas.ts b/src/new_fields/documentSchemas.ts index 81f073855..3cc05d3d5 100644 --- a/src/new_fields/documentSchemas.ts +++ b/src/new_fields/documentSchemas.ts @@ -4,12 +4,13 @@ import { Doc } from "./Doc"; import { DateField } from "./DateField"; export const documentSchema = createSchema({ - layout: "string", // this is the native layout string for the document. templates can be added using other fields and setting layoutKey below (see layout_custom as an example) + type: "string", // enumerated type of document -- should be template-specific (ie, start with an '_') + layout: "string", // this is the native layout string for the document. templates can be added using other fields and setting layoutKey below layoutKey: "string", // holds the field key for the field that actually holds the current lyoat - layout_custom: Doc, // used to hold a custom layout (there's nothing special about this field .. any field could hold a custom layout that can be selected by setting 'layoutKey') title: "string", // document title (can be on either data document or layout) dropAction: "string", // override specifying what should happen when this document is dropped (can be "alias" or "copy") childDropAction: "string", // specify the override for what should happen when the child of a collection is dragged from it and dropped (can be "alias" or "copy") + _autoHeight: "boolean", // whether the height of the document should be computed automatically based on its contents _nativeWidth: "number", // native width of document which determines how much document contents are scaled when the document's width is set _nativeHeight: "number", // " _width: "number", // width of document in its container's coordinate system @@ -27,20 +28,18 @@ export const documentSchema = createSchema({ opacity: "number", // opacity of document creationDate: DateField, // when the document was created links: listSpec(Doc), // computed (readonly) list of links associated with this document - removeDropProperties: listSpec("string"), // properties that should be removed from the alias/copy/etc of this document when it is dropped onClick: ScriptField, // script to run when document is clicked (can be overriden by an onClick prop) onPointerDown: ScriptField, // script to run when document is clicked (can be overriden by an onClick prop) onPointerUp: ScriptField, // script to run when document is clicked (can be overriden by an onClick prop) onDragStart: ScriptField, // script to run when document is dragged (without being selected). the script should return the Doc to be dropped. dragFactory: Doc, // the document that serves as the "template" for the onDragStart script. ie, to drag out copies of the dragFactory document. + removeDropProperties: listSpec("string"), // properties that should be removed from the alias/copy/etc of this document when it is dropped ignoreAspect: "boolean", // whether aspect ratio should be ignored when laying out or manipulating the document - autoHeight: "boolean", // whether the height of the document should be computed automatically based on its contents isTemplateForField: "string",// when specifies a field key, then the containing document is a template that renders the specified field isBackground: "boolean", // whether document is a background element and ignores input events (can only selet with marquee) - type: "string", // enumerated type of document treeViewOpen: "boolean", // flag denoting whether the documents sub-tree (contents) is visible or hidden treeViewExpandedView: "string", // name of field whose contents are being displayed as the document's subtree - preventTreeViewOpen: "boolean", // ignores the treeViewOpen flag (for allowing a view to not be slaved to other views of the document) + treeViewPreventOpen: "boolean", // ignores the treeViewOpen flag (for allowing a view to not be slaved to other views of the document) currentTimecode: "number", // current play back time of a temporal document (video / audio) maximizeLocation: "string", // flag for where to place content when following a click interaction (e.g., onRight, inPlace, inTab) lockedPosition: "boolean", // whether the document can be moved (dragged) @@ -57,7 +56,6 @@ export const documentSchema = createSchema({ fitToBox: "boolean", // whether freeform view contents should be zoomed/panned to fill the area of the document view xPadding: "number", // pixels of padding on left/right of collectionfreeformview contents when fitToBox is set yPadding: "number", // pixels of padding on left/right of collectionfreeformview contents when fitToBox is set - LODarea: "number", // area (width*height) where CollectionFreeFormViews switch from a label to rendering contents letterSpacing: "string", textTransform: "string" }); diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 45875d455..32c375bd7 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -139,7 +139,7 @@ export class CurrentUserUtils { static setupThumbDoc(userDoc: Doc) { if (!userDoc.thumbDoc) { userDoc.thumbDoc = Docs.Create.LinearDocument(CurrentUserUtils.setupThumbButtons(userDoc), { - _width: 100, _height: 50, ignoreClick: true, lockedPosition: true, _chromeStatus: "disabled", title: "buttons", _autoHeight: true, _yMargin: 5, isExpanded: true, backgroundColor: "white" + _width: 100, _height: 50, ignoreClick: true, lockedPosition: true, _chromeStatus: "disabled", title: "buttons", _autoHeight: true, _yMargin: 5, linearViewIsExpanded: true, backgroundColor: "white" }); } return userDoc.thumbDoc; @@ -181,12 +181,12 @@ export class CurrentUserUtils { }); doc.documents = Docs.Create.TreeDocument([], { - title: "DOCUMENTS", _height: 42, forceActive: true, boxShadow: "0 0", preventTreeViewOpen: true, lockedPosition: true, backgroundColor: "#eeeeee" + title: "DOCUMENTS", _height: 42, forceActive: true, boxShadow: "0 0", treeViewPreventOpen: true, lockedPosition: true, backgroundColor: "#eeeeee" }); // setup Recently Closed library item doc.recentlyClosed = Docs.Create.TreeDocument([], { - title: "RECENTLY CLOSED", _height: 75, forceActive: true, boxShadow: "0 0", preventTreeViewOpen: true, lockedPosition: true, backgroundColor: "#eeeeee" + title: "RECENTLY CLOSED", _height: 75, forceActive: true, boxShadow: "0 0", treeViewPreventOpen: true, lockedPosition: true, backgroundColor: "#eeeeee" }); return Docs.Create.ButtonDocument({ @@ -255,7 +255,7 @@ export class CurrentUserUtils { { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: slideTemplate, removeDropProperties: new List(["dropAction"]), title: "presentation slide", icon: "sticky-note" }); doc.expandingButtons = Docs.Create.LinearDocument([doc.undoBtn as Doc, doc.redoBtn as Doc, doc.slidesBtn as Doc], { title: "expanding buttons", _gridGap: 5, _xMargin: 5, _yMargin: 5, _height: 42, _width: 100, boxShadow: "0 0", - backgroundColor: "black", preventTreeViewOpen: true, forceActive: true, lockedPosition: true, + backgroundColor: "black", treeViewPreventOpen: true, forceActive: true, lockedPosition: true, dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }) }); -- cgit v1.2.3-70-g09d2 From 8034deb2249b23e418427c4713c84f1ad76223c2 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Sat, 15 Feb 2020 14:43:42 -0500 Subject: fixed dark scheme a bit more. fixed entering metadata on goldenlayout tabs --- src/client/util/DocumentManager.ts | 2 +- src/client/views/DocumentButtonBar.tsx | 2 +- src/client/views/DocumentDecorations.scss | 4 ++ src/client/views/DocumentDecorations.tsx | 62 +++++++++++++--------- src/client/views/MainView.scss | 9 +++- src/client/views/MainView.tsx | 8 +-- src/client/views/MetadataEntryMenu.scss | 6 +++ src/client/views/MetadataEntryMenu.tsx | 25 ++++----- .../CollectionStackingViewFieldColumn.tsx | 2 +- .../views/collections/ParentDocumentSelector.tsx | 5 +- src/client/views/nodes/ButtonBox.tsx | 2 +- .../authentication/models/current_user_utils.ts | 14 ++--- 12 files changed, 84 insertions(+), 57 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/util/DocumentManager.ts b/src/client/util/DocumentManager.ts index 60bb25272..d66bb3f09 100644 --- a/src/client/util/DocumentManager.ts +++ b/src/client/util/DocumentManager.ts @@ -208,7 +208,7 @@ export class DocumentManager { @action zoomIntoScale = (docDelegate: Doc, scale: number) => { const docView = DocumentManager.Instance.getDocumentView(Doc.GetProto(docDelegate)); - docView && docView.props.zoomToScale(scale); + docView?.props.zoomToScale(scale); } getScaleOfDocView = (docDelegate: Doc) => { diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx index 2201fe710..ec1f879c2 100644 --- a/src/client/views/DocumentButtonBar.tsx +++ b/src/client/views/DocumentButtonBar.tsx @@ -242,7 +242,7 @@ export class DocumentButtonBar extends React.Component<{ views: (DocumentView | return !view0 ? (null) :
this.props.views.filter(dv => dv).map(dv => dv!.props.Document)} suggestWithFunction /> /* tfs: @bcz This might need to be the data document? */}> -
+
e.stopPropagation()} > {}
diff --git a/src/client/views/DocumentDecorations.scss b/src/client/views/DocumentDecorations.scss index 455e53a79..c847dd4d0 100644 --- a/src/client/views/DocumentDecorations.scss +++ b/src/client/views/DocumentDecorations.scss @@ -259,6 +259,10 @@ $linkGap : 3px; } } +.documentDecorations-darkScheme { + background: dimgray; +} + #template-list { position: absolute; top: 25px; diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 65c02591c..12427cdac 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -479,17 +479,29 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> return ; } render() { + const darkScheme = Cast(Doc.UserDoc().activeWorkspace, Doc, null)?.darkScheme ? "dimgray" : undefined; const bounds = this.Bounds; const seldoc = SelectionManager.SelectedDocuments().length ? SelectionManager.SelectedDocuments()[0] : undefined; if (SelectionManager.GetIsDragging() || bounds.x === Number.MAX_VALUE || !seldoc || this._hidden || isNaN(bounds.r) || isNaN(bounds.b) || isNaN(bounds.x) || isNaN(bounds.y)) { return (null); } const minimizeIcon = ( -
+
{/* Currently, this is set to be enabled if there is no ink selected. It might be interesting to think about minimizing ink if it's useful? -syip2*/} - {SelectionManager.SelectedDocuments().length === 1 ? DocumentDecorations.DocumentIcon(StrCast(SelectionManager.SelectedDocuments()[0].props.Document.layout, "...")) : "..."} + {SelectionManager.SelectedDocuments().length === 1 ? DocumentDecorations.DocumentIcon(StrCast(seldoc.props.Document.layout, "...")) : "..."}
); + const titleArea = this._edtingTitle ? + <> + this.titleBlur(true)} onChange={this.titleChanged} onKeyPress={this.titleEntered} /> +
DocUtils.Publish(seldoc.props.Document, this._accumulatedTitle, seldoc.props.addDocument, seldoc.props.removeDocument)}> + +
+ : +
{`${this.selectionTitle}`}
; + bounds.x = Math.max(0, bounds.x - this._resizeBorderWidth / 2) + this._resizeBorderWidth / 2; bounds.y = Math.max(0, bounds.y - this._resizeBorderWidth / 2 - this._titleHeight) + this._resizeBorderWidth / 2 + this._titleHeight; const borderRadiusDraggerWidth = 15; @@ -519,38 +531,36 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> opacity: this._opacity }}> {minimizeIcon} - - {this._edtingTitle ? <> - this.titleBlur(true)} onChange={this.titleChanged} onKeyPress={this.titleEntered} /> -
{ - const promoteDoc = SelectionManager.SelectedDocuments()[0]; - DocUtils.Publish(promoteDoc.props.Document, this._accumulatedTitle, promoteDoc.props.addDocument, promoteDoc.props.removeDocument); - }}> - -
- : -
{`${this.selectionTitle}`}
} -
+ {titleArea} +
-
e.preventDefault()}>
-
e.preventDefault()}>
-
e.preventDefault()}>
-
e.preventDefault()}>
+
e.preventDefault()}>
+
e.preventDefault()}>
+
e.preventDefault()}>
+
e.preventDefault()}>
-
e.preventDefault()}>
-
e.preventDefault()}>
-
e.preventDefault()}>
-
e.preventDefault()}>
-
e.preventDefault()}>
+
e.preventDefault()}>
+
e.preventDefault()}>
+
e.preventDefault()}>
+
e.preventDefault()}>
+
e.preventDefault()}>
-
+
); } } \ No newline at end of file diff --git a/src/client/views/MainView.scss b/src/client/views/MainView.scss index d39c217ec..b8fd7be0b 100644 --- a/src/client/views/MainView.scss +++ b/src/client/views/MainView.scss @@ -21,7 +21,7 @@ z-index: 1; } -#mainView-container { +.mainView-container, .mainView-container-dark { width: 100%; height: 100%; position: absolute; @@ -31,6 +31,13 @@ touch-action: none; } +.mainView-container-dark { + .lm_splitter { + background: dimgray; + opacity: 0.5; + } +} + .mainView-mainContent { width: 100%; height: 100%; diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index ba49a2b53..5d739474e 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -276,7 +276,7 @@ export class MainView extends React.Component { childBackgroundColor = (doc: Doc) => { if (this.darkScheme) { - return doc.type === DocumentType.TEXT ? "#112423" : "black"; + return doc.type === DocumentType.TEXT ? "#2d2d2d" : "black"; } return doc.type === DocumentType.TEXT ? "#f1efeb" : doc.type === DocumentType.COL && doc._viewType === CollectionViewType.Tree ? "lightgray" : "white"; @@ -448,10 +448,10 @@ export class MainView extends React.Component { @computed get mainContent() { const sidebar = this.userDoc && this.userDoc.sidebarContainer; return !this.userDoc || !(sidebar instanceof Doc) ? (null) : ( -
+
+ style={{ backgroundColor: `${StrCast(sidebar.backgroundColor, this.darkScheme ? "dimGray" : "black")}` }} > + return (
diff --git a/src/client/views/MetadataEntryMenu.scss b/src/client/views/MetadataEntryMenu.scss index 5f4a52c0c..5776cf070 100644 --- a/src/client/views/MetadataEntryMenu.scss +++ b/src/client/views/MetadataEntryMenu.scss @@ -8,6 +8,12 @@ } } +.metadataEntry-autoSuggester { + width: 100%; + height: 100%; + padding-right: 10px; +} + #metadataEntry-outer { overflow: auto !important; } diff --git a/src/client/views/MetadataEntryMenu.tsx b/src/client/views/MetadataEntryMenu.tsx index 23b21ae0c..8bc80ed06 100644 --- a/src/client/views/MetadataEntryMenu.tsx +++ b/src/client/views/MetadataEntryMenu.tsx @@ -195,10 +195,10 @@ export class MetadataEntryMenu extends React.Component{ _ref = React.createRef(); render() { - return ( -
-
- Key: + return (
e.stopPropagation()}> +
+ Key: +
this.autosuggestRef.current!.input?.focus()} > { onSuggestionsFetchRequested={emptyFunction} onSuggestionsClearRequested={emptyFunction} ref={this.autosuggestRef} /> - Value: - this._ref.current!.focus()} onChange={this.onValueChange} onKeyDown={this.onValueKeyDown} /> - {this.considerChildOptions} -
-
-
    - {this._allSuggestions.slice().sort().map(s =>
  • { this._currentKey = s; this.previewValue(); })} >{s}
  • )} -
+ Value: + this._ref.current!.focus()} onChange={this.onValueChange} onKeyDown={this.onValueKeyDown} /> + {this.considerChildOptions} +
+
+
    + {this._allSuggestions.slice().sort().map(s =>
  • { this._currentKey = s; this.previewValue(); })} >{s}
  • )} +
+
); } } \ No newline at end of file diff --git a/src/client/views/collections/CollectionStackingViewFieldColumn.tsx b/src/client/views/collections/CollectionStackingViewFieldColumn.tsx index 3fc05c6b7..2ff477c57 100644 --- a/src/client/views/collections/CollectionStackingViewFieldColumn.tsx +++ b/src/client/views/collections/CollectionStackingViewFieldColumn.tsx @@ -360,7 +360,7 @@ export class CollectionStackingViewFieldColumn extends React.Component diff --git a/src/client/views/collections/ParentDocumentSelector.tsx b/src/client/views/collections/ParentDocumentSelector.tsx index 6e406638b..41b9e821c 100644 --- a/src/client/views/collections/ParentDocumentSelector.tsx +++ b/src/client/views/collections/ParentDocumentSelector.tsx @@ -78,13 +78,12 @@ export class SelectorContextMenu extends React.Component { export class ParentDocSelector extends React.Component { render() { const flyout = ( -
+
); return
e.stopPropagation()} className="parentDocumentSelector-linkFlyout"> - + diff --git a/src/client/views/nodes/ButtonBox.tsx b/src/client/views/nodes/ButtonBox.tsx index ee48b47b7..de0b509eb 100644 --- a/src/client/views/nodes/ButtonBox.tsx +++ b/src/client/views/nodes/ButtonBox.tsx @@ -81,7 +81,7 @@ export class ButtonBox extends DocComponent(Butt
diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 32c375bd7..d09837d96 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -164,7 +164,7 @@ export class CurrentUserUtils { }); return Docs.Create.ButtonDocument({ - _width: 35, _height: 25, backgroundColor: "lightgrey", color: "rgb(34, 34, 34)", title: "Tools", fontSize: 10, targetContainer: sidebarContainer, + _width: 35, _height: 25, title: "Tools", fontSize: 10, targetContainer: sidebarContainer, letterSpacing: "0px", textTransform: "unset", borderRounding: "5px 5px 0px 0px", boxShadow: "3px 3px 0px rgb(34, 34, 34)", sourcePanel: Docs.Create.StackingDocument([dragCreators, color], { _width: 500, lockedPosition: true, _chromeStatus: "disabled", title: "tools stack" @@ -177,20 +177,20 @@ export class CurrentUserUtils { static setupLibraryPanel(sidebarContainer: Doc, doc: Doc) { // setup workspaces library item doc.workspaces = Docs.Create.TreeDocument([], { - title: "WORKSPACES", _height: 100, forceActive: true, boxShadow: "0 0", lockedPosition: true, backgroundColor: "#eeeeee" + title: "WORKSPACES", _height: 100, forceActive: true, boxShadow: "0 0", lockedPosition: true, }); doc.documents = Docs.Create.TreeDocument([], { - title: "DOCUMENTS", _height: 42, forceActive: true, boxShadow: "0 0", treeViewPreventOpen: true, lockedPosition: true, backgroundColor: "#eeeeee" + title: "DOCUMENTS", _height: 42, forceActive: true, boxShadow: "0 0", treeViewPreventOpen: true, lockedPosition: true, }); // setup Recently Closed library item doc.recentlyClosed = Docs.Create.TreeDocument([], { - title: "RECENTLY CLOSED", _height: 75, forceActive: true, boxShadow: "0 0", treeViewPreventOpen: true, lockedPosition: true, backgroundColor: "#eeeeee" + title: "RECENTLY CLOSED", _height: 75, forceActive: true, boxShadow: "0 0", treeViewPreventOpen: true, lockedPosition: true, }); return Docs.Create.ButtonDocument({ - _width: 50, _height: 25, backgroundColor: "lightgrey", color: "rgb(34, 34, 34)", title: "Library", fontSize: 10, + _width: 50, _height: 25, title: "Library", fontSize: 10, letterSpacing: "0px", textTransform: "unset", borderRounding: "5px 5px 0px 0px", boxShadow: "3px 3px 0px rgb(34, 34, 34)", sourcePanel: Docs.Create.TreeDocument([doc.workspaces as Doc, doc.documents as Doc, doc.recentlyClosed as Doc], { title: "Library", _xMargin: 5, _yMargin: 5, _gridGap: 5, forceActive: true, dropAction: "alias", lockedPosition: true, boxShadow: "0 0", @@ -203,7 +203,7 @@ export class CurrentUserUtils { // setup the Search button which will display the search panel. static setupSearchPanel(sidebarContainer: Doc) { return Docs.Create.ButtonDocument({ - _width: 50, _height: 25, backgroundColor: "lightgrey", color: "rgb(34, 34, 34)", title: "Search", fontSize: 10, + _width: 50, _height: 25, title: "Search", fontSize: 10, letterSpacing: "0px", textTransform: "unset", borderRounding: "5px 5px 0px 0px", boxShadow: "3px 3px 0px rgb(34, 34, 34)", sourcePanel: Docs.Create.QueryDocument({ title: "search stack", ignoreClick: true @@ -239,7 +239,7 @@ export class CurrentUserUtils { Docs.Create.MulticolumnDocument([], { title: "images", _height: 200 }), Docs.Create.TextDocument("", { title: "contents", _height: 100 }) ], - { _width: 400, _height: 300, title: "slideView", _chromeStatus: "disabled", _xMargin: 3, _yMargin: 3, backgroundColor: "lightGray", _autoHeight: true }); + { _width: 400, _height: 300, title: "slideView", _chromeStatus: "disabled", _xMargin: 3, _yMargin: 3, _autoHeight: true }); slideTemplate.isTemplateDoc = makeTemplate(slideTemplate); const iconDoc = Docs.Create.TextDocument("", { title: "icon", _width: 150, _height: 30, isTemplateDoc: true, onClick: ScriptField.MakeScript("setNativeView(this)") }); -- cgit v1.2.3-70-g09d2 From 286b1a69b5b300b414fe299efa3ae018d55c90be Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Sat, 15 Feb 2020 20:21:24 -0500 Subject: title bar fixes and more dark scheme stuff --- src/client/goldenLayout.js | 2 +- src/client/views/MainView.scss | 6 +++-- src/client/views/MainView.tsx | 5 ++-- .../views/collections/CollectionDockingView.scss | 20 +++++++++++++--- .../views/collections/CollectionDockingView.tsx | 27 +++++++++++----------- src/client/views/collections/CollectionView.tsx | 3 ++- .../authentication/models/current_user_utils.ts | 2 +- 7 files changed, 41 insertions(+), 24 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/goldenLayout.js b/src/client/goldenLayout.js index 29b750720..b510385ff 100644 --- a/src/client/goldenLayout.js +++ b/src/client/goldenLayout.js @@ -2868,7 +2868,7 @@ * @type {String} */ lm.controls.Tab._template = '
  • ' + - '
    ' + + '
    ' + '
  • '; lm.utils.copy(lm.controls.Tab.prototype, { diff --git a/src/client/views/MainView.scss b/src/client/views/MainView.scss index b8fd7be0b..df594be4d 100644 --- a/src/client/views/MainView.scss +++ b/src/client/views/MainView.scss @@ -32,9 +32,11 @@ } .mainView-container-dark { - .lm_splitter { + .lm_goldenlayout { background: dimgray; - opacity: 0.5; + } + .marquee { + border-color: white; } } diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 5d739474e..de76106d1 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -276,10 +276,11 @@ export class MainView extends React.Component { childBackgroundColor = (doc: Doc) => { if (this.darkScheme) { - return doc.type === DocumentType.TEXT ? "#2d2d2d" : "black"; + return doc.type === DocumentType.TEXT || doc.type === DocumentType.BUTTON ? "#2d2d2d" : + (doc.type === DocumentType.COL && doc._viewType !== CollectionViewType.Freeform && doc._viewType !== CollectionViewType.Time) || doc.type === DocumentType.BUTTON ? "#2d2d2d" : "black"; } return doc.type === DocumentType.TEXT ? "#f1efeb" : - doc.type === DocumentType.COL && doc._viewType === CollectionViewType.Tree ? "lightgray" : "white"; + (doc.type === DocumentType.COL && doc._viewType !== CollectionViewType.Freeform && doc._viewType !== CollectionViewType.Time) || doc.type === DocumentType.BUTTON ? "lightgray" : "white"; } sidebarBackgroundColor = (doc: Doc) => { return this.childBackgroundColor(doc); diff --git a/src/client/views/collections/CollectionDockingView.scss b/src/client/views/collections/CollectionDockingView.scss index 819332d86..2fafcecb2 100644 --- a/src/client/views/collections/CollectionDockingView.scss +++ b/src/client/views/collections/CollectionDockingView.scss @@ -1,8 +1,22 @@ @import "../../views/globalCssVariables.scss"; -.lm_active .messageCounter { - color: white; - background: #999999; +.lm_title { + margin-top: 3px; + background: black; + border-radius: 5px; + border: solid 1px dimgray; + border-width: 2px 2px 0px; + height: 20px; + transform: translate(0px, -3px); +} +.lm_title_wrap { + overflow: hidden; + height: 19px; + margin-top: -3px; + display:inline-block; +} +.lm_active .lm_title { + border: solid 1px lightgray; } .lm_header .lm_tab .lm_close_tab { position: absolute; diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 67a7577eb..6abfb59c3 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -379,16 +379,6 @@ export class CollectionDockingView extends React.Component) => - (sourceDoc instanceof Doc) && DragManager.StartLinkTargetsDrag(tab, x, y, sourceDoc))); - } if (className === "lm_drag_handle" || className === "lm_close" || className === "lm_maximise" || className === "lm_minimise" || className === "lm_close_tab") { this._flush = true; } @@ -430,6 +420,7 @@ export class CollectionDockingView extends React.Component { + tab.titleElement[0].Tab = tab; if (tab.hasOwnProperty("contentItem") && tab.contentItem.config.type !== "stack") { if (tab.contentItem.config.fixed) { tab.contentItem.parent.config.fixed = true; @@ -438,6 +429,14 @@ export class CollectionDockingView extends React.Component`; + tab.titleElement[0].onclick = (e: any) => tab.titleElement[0].focus(); + tab.titleElement[0].onchange = (e: any) => { + tab.titleElement[0].size = e.currentTarget.value.length + 1; + Doc.SetInPlace(doc, "title", e.currentTarget.value, true); + } + tab.titleElement[0].size = StrCast(doc.title).length + 1; + tab.titleElement[0].value = doc.title; const gearSpan = document.createElement("span"); gearSpan.className = "collectionDockingView-gear"; gearSpan.style.position = "relative"; @@ -464,15 +463,15 @@ export class CollectionDockingView extends React.Component, gearSpan); tab.reactComponents = [gearSpan]; tab.element.append(gearSpan); - tab.reactionDisposer = reaction(() => [doc.title, Doc.IsBrushedDegree(doc)], () => { - tab.titleElement[0].textContent = doc.title, { fireImmediately: true }; - tab.titleElement[0].style.outline = `${["transparent", "white", "white"][Doc.IsBrushedDegreeUnmemoized(doc)]} ${["none", "dashed", "solid"][Doc.IsBrushedDegreeUnmemoized(doc)]} 1px`; + tab.reactionDisposer = reaction(() => ({ title: doc.title, degree: Doc.IsBrushedDegree(doc) }), ({ title, degree }) => { + tab.titleElement[0].textContent = title, { fireImmediately: true }; + tab.titleElement[0].style.padding = degree ? 0 : 2; + tab.titleElement[0].style.border = `${["gray", "gray", "gray"][degree]} ${["none", "dashed", "solid"][degree]} 2px`; }); //TODO why can't this just be doc instead of the id? tab.titleElement[0].DashDocId = tab.contentItem.config.props.documentId; } } - tab.titleElement[0].Tab = tab; tab.closeElement.off('click') //unbind the current click handler .click(async function () { tab.reactionDisposer && tab.reactionDisposer(); diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index be971eda6..48294f9c2 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -293,7 +293,8 @@ export class CollectionView extends Touchable { return (
    {this.showIsTagged()} diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index d09837d96..888e27f28 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -227,7 +227,7 @@ export class CurrentUserUtils { // Finally, setup the list of buttons to display in the sidebar doc.sidebarButtons = Docs.Create.StackingDocument([doc.SearchBtn as Doc, doc.LibraryBtn as Doc, doc.ToolsBtn as Doc], { _width: 500, _height: 80, boxShadow: "0 0", sectionFilter: "title", hideHeadings: true, ignoreClick: true, - backgroundColor: "rgb(100, 100, 100)", _chromeStatus: "disabled", title: "library stack", + _chromeStatus: "disabled", title: "library stack", _yMargin: 10, }); } -- cgit v1.2.3-70-g09d2 From a71f1cbfe47bbe5bcefa7deb63fa812683a37178 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Sat, 15 Feb 2020 22:44:33 -0500 Subject: more color scheme fixes. --- src/client/documents/DocumentTypes.ts | 1 - src/client/views/DocumentDecorations.tsx | 24 +++++++------- src/client/views/MainView.scss | 16 ++++++++++ src/client/views/MainView.tsx | 37 ++++++++++++++-------- src/client/views/nodes/DocumentView.tsx | 4 ++- src/client/views/search/FilterBox.tsx | 2 +- src/client/views/search/SearchBox.tsx | 2 +- .../authentication/models/current_user_utils.ts | 3 +- 8 files changed, 57 insertions(+), 32 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/documents/DocumentTypes.ts b/src/client/documents/DocumentTypes.ts index 1220e9923..0e6b59b33 100644 --- a/src/client/documents/DocumentTypes.ts +++ b/src/client/documents/DocumentTypes.ts @@ -14,7 +14,6 @@ export enum DocumentType { LINKDOC = "linkdoc", BUTTON = "button", SLIDER = "slider", - TEMPLATE = "template", EXTENSION = "extension", YOUTUBE = "youtube", WEBCAM = "webcam", diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 12427cdac..3388ea46c 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -491,16 +491,16 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> {SelectionManager.SelectedDocuments().length === 1 ? DocumentDecorations.DocumentIcon(StrCast(seldoc.props.Document.layout, "...")) : "..."}
    ); - const titleArea = this._edtingTitle ? - <> - this.titleBlur(true)} onChange={this.titleChanged} onKeyPress={this.titleEntered} /> -
    DocUtils.Publish(seldoc.props.Document, this._accumulatedTitle, seldoc.props.addDocument, seldoc.props.removeDocument)}> - -
    - : -
    {`${this.selectionTitle}`}
    ; + const titleArea = this._edtingTitle ? + <> + this.titleBlur(true)} onChange={this.titleChanged} onKeyPress={this.titleEntered} /> +
    DocUtils.Publish(seldoc.props.Document, this._accumulatedTitle, seldoc.props.addDocument, seldoc.props.removeDocument)}> + +
    + : +
    {`${this.selectionTitle}`}
    ; bounds.x = Math.max(0, bounds.x - this._resizeBorderWidth / 2) + this._resizeBorderWidth / 2; bounds.y = Math.max(0, bounds.y - this._resizeBorderWidth / 2 - this._titleHeight) + this._resizeBorderWidth / 2 + this._titleHeight; @@ -539,7 +539,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }>
    e.preventDefault()}>
    e.preventDefault()}>
    + style={{ background: darkScheme }} onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}>
    e.preventDefault()}>
    e.preventDefault()}>
    e.preventDefault()}>
    + style={{ background: darkScheme }} onPointerDown={this.onRadiusDown} onContextMenu={(e) => e.preventDefault()}>
    diff --git a/src/client/views/MainView.scss b/src/client/views/MainView.scss index df594be4d..e91f7e94c 100644 --- a/src/client/views/MainView.scss +++ b/src/client/views/MainView.scss @@ -29,6 +29,9 @@ left: 0; z-index: 1; touch-action: none; + .searchBox-container { + background: lightgray; + } } .mainView-container-dark { @@ -38,6 +41,19 @@ .marquee { border-color: white; } + #search-input { + background: lightgray; + } + .searchBox-container { + background: rgb(45,45,45); + } + .contextMenu-cont, .contextMenu-item { + background: dimGray; + color: lightgray; + } + .contextMenu-item:hover { + background: gray; + } } .mainView-mainContent { diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index de76106d1..7948da3c5 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -274,16 +274,25 @@ export class MainView extends React.Component { getPHeight = () => this._panelHeight; getContentsHeight = () => this._panelHeight - this._buttonBarHeight; - childBackgroundColor = (doc: Doc) => { + defaultBackgroundColors = (doc: Doc) => { if (this.darkScheme) { - return doc.type === DocumentType.TEXT || doc.type === DocumentType.BUTTON ? "#2d2d2d" : - (doc.type === DocumentType.COL && doc._viewType !== CollectionViewType.Freeform && doc._viewType !== CollectionViewType.Time) || doc.type === DocumentType.BUTTON ? "#2d2d2d" : "black"; + switch (doc.type) { + case DocumentType.TEXT || DocumentType.BUTTON: return "#2d2d2d"; + case DocumentType.COL: { + if (doc._viewType !== CollectionViewType.Freeform && doc._viewType !== CollectionViewType.Time) return "rgb(62,62,62)"; + } + default: return "black"; + } + } else { + switch (doc.type) { + case DocumentType.TEXT: return "#f1efeb"; + case DocumentType.BUTTON: return "lightgray"; + case DocumentType.COL: { + if (doc._viewType !== CollectionViewType.Freeform && doc._viewType !== CollectionViewType.Time) return "lightgray"; + } + default: return "white"; + } } - return doc.type === DocumentType.TEXT ? "#f1efeb" : - (doc.type === DocumentType.COL && doc._viewType !== CollectionViewType.Freeform && doc._viewType !== CollectionViewType.Time) || doc.type === DocumentType.BUTTON ? "lightgray" : "white"; - } - sidebarBackgroundColor = (doc: Doc) => { - return this.childBackgroundColor(doc); } @computed get mainDocView() { return -
    +
    ; } - + //`${StrCast(sidebar.backgroundColor, this.darkScheme ? "dimGray" : "black")}` }} > @computed get mainContent() { const sidebar = this.userDoc && this.userDoc.sidebarContainer; return !this.userDoc || !(sidebar instanceof Doc) ? (null) : (
    + style={{ backgroundColor: this.defaultBackgroundColors(sidebar) }}> (Docu const borderRounding = this.layoutDoc.borderRounding; const localScale = fullDegree; - const highlightColors = ["transparent", "maroon", "maroon", "yellow", "magenta", "cyan", "orange"]; + const highlightColors = Cast(Doc.UserDoc().activeWorkspace, Doc, null)?.darkScheme ? + ["transparent", "#65350c", "#65350c", "yellow", "magenta", "cyan", "orange"] : + ["transparent", "maroon", "maroon", "yellow", "magenta", "cyan", "orange"]; const highlightStyles = ["solid", "dashed", "solid", "solid", "solid", "solid", "solid"]; let highlighting = fullDegree && this.layoutDoc.type !== DocumentType.FONTICON && this.layoutDoc._viewType !== CollectionViewType.Linear; highlighting = highlighting && this.props.focus !== emptyFunction; // bcz: hack to turn off highlighting onsidebar panel documents. need to flag a document as not highlightable in a more direct way diff --git a/src/client/views/search/FilterBox.tsx b/src/client/views/search/FilterBox.tsx index 684f50766..d4c9e67fb 100644 --- a/src/client/views/search/FilterBox.tsx +++ b/src/client/views/search/FilterBox.tsx @@ -33,7 +33,7 @@ export enum Keys { export class FilterBox extends React.Component { static Instance: FilterBox; - public _allIcons: string[] = [DocumentType.AUDIO, DocumentType.COL, DocumentType.IMG, DocumentType.LINK, DocumentType.PDF, DocumentType.TEXT, DocumentType.VID, DocumentType.WEB, DocumentType.TEMPLATE]; + public _allIcons: string[] = [DocumentType.AUDIO, DocumentType.COL, DocumentType.IMG, DocumentType.LINK, DocumentType.PDF, DocumentType.TEXT, DocumentType.VID, DocumentType.WEB]; //if true, any keywords can be used. if false, all keywords are required. //this also serves as an indicator if the word status filter is applied diff --git a/src/client/views/search/SearchBox.tsx b/src/client/views/search/SearchBox.tsx index be13dae03..9bd42b516 100644 --- a/src/client/views/search/SearchBox.tsx +++ b/src/client/views/search/SearchBox.tsx @@ -234,7 +234,7 @@ export class SearchBox extends React.Component { y += 300; } } - return Docs.Create.TreeDocument(docs, { _width: 200, _height: 400, backgroundColor: "grey", title: `Search Docs: "${this._searchString}"` }); + return Docs.Create.TreeDocument(docs, { _width: 200, _height: 400, title: `Search Docs: "${this._searchString}"` }); } @action.bound diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 888e27f28..930b021a4 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -227,8 +227,7 @@ export class CurrentUserUtils { // Finally, setup the list of buttons to display in the sidebar doc.sidebarButtons = Docs.Create.StackingDocument([doc.SearchBtn as Doc, doc.LibraryBtn as Doc, doc.ToolsBtn as Doc], { _width: 500, _height: 80, boxShadow: "0 0", sectionFilter: "title", hideHeadings: true, ignoreClick: true, - _chromeStatus: "disabled", title: "library stack", - _yMargin: 10, + _chromeStatus: "disabled", title: "library stack", backgroundColor: "dimGray", }); } -- cgit v1.2.3-70-g09d2 From 266892f40d5abc9f8ce4cbb2d6fb70564ecd8da3 Mon Sep 17 00:00:00 2001 From: bob Date: Mon, 17 Feb 2020 19:45:30 -0500 Subject: fixed initialization of note types and alias titles. --- src/client/views/collections/collectionFreeForm/MarqueeView.tsx | 2 +- src/server/authentication/models/current_user_utils.ts | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx index a29823734..b1e4ca9db 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -74,7 +74,7 @@ export class MarqueeView extends React.Component ({ description: ":" + (i + 1) + " " + StrCast(note.title), - event: (args: { x: number, y: number }) => this.props.addLiveTextDocument(Docs.Create.TextDocument("", { _width: 200, _height: 100, x, y, _autoHeight: true, layout: note, title: StrCast(note.title) })), + event: (args: { x: number, y: number }) => this.props.addLiveTextDocument(Docs.Create.TextDocument("", { _width: 200, _height: 100, x, y, _autoHeight: true, layout: note, title: StrCast(note.title) + "#" + (note.aliasCount = NumCast(note.aliasCount) + 1) })), icon: "eye" })) as ContextMenuProps[], icon: "eye" diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 930b021a4..66d1129f2 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -44,13 +44,15 @@ export class CurrentUserUtils { Docs.Create.TextDocument("", { title: "Todo", backgroundColor: "orange", isTemplateDoc: true }) ]; } + static setupDefaultDocTemplates(doc: Doc, buttons?: string[]) { + doc.noteTypes = new PrefetchProxy(Docs.Create.TreeDocument(CurrentUserUtils.setupNoteTypes(doc), { title: "Note Types", _height: 75 })); + } // setup the "creator" buttons for the sidebar-- eg. the default set of draggable document creation tools static setupCreatorButtons(doc: Doc, buttons?: string[]) { - const notes = CurrentUserUtils.setupNoteTypes(doc); + const notes = DocListCast(Cast(doc.noteTypes, Doc, null)?.data); const emptyPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, _LODdisable: true, _chromeStatus: "replaced", _showTitle: "title", boxShadow: "0 0" }); const emptyCollection = Docs.Create.FreeformDocument([], { _nativeWidth: undefined, _nativeHeight: undefined, _LODdisable: true, _width: 150, _height: 100, title: "freeform" }); - doc.noteTypes = Docs.Create.TreeDocument(notes, { title: "Note Types", _height: 75 }); doc.activePen = doc; const docProtoData: { title: string, icon: string, drag?: string, ignoreClick?: boolean, click?: string, ischecked?: string, activePen?: Doc, backgroundColor?: string, dragFactory?: Doc }[] = [ { title: "collection", icon: "folder", click: 'openOnRight(getCopy(this.dragFactory, true))', drag: 'getCopy(this.dragFactory, true)', dragFactory: emptyCollection }, @@ -280,6 +282,7 @@ export class CurrentUserUtils { static updateUserDocument(doc: Doc) { doc.title = Doc.CurrentUserEmail; new InkingControl(); + (doc.noteTypes === undefined) && CurrentUserUtils.setupDefaultDocTemplates(doc); (doc.optionalRightCollection === undefined) && CurrentUserUtils.setupMobileUploads(doc); (doc.overlays === undefined) && CurrentUserUtils.setupOverlays(doc); (doc.expandingButtons === undefined) && CurrentUserUtils.setupExpandingButtons(doc); -- cgit v1.2.3-70-g09d2 From 0f2872775a9a3bab73c92afc329e1279645f3a71 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Mon, 17 Feb 2020 22:50:10 -0500 Subject: made creation of template docs from context menu simpler --- src/client/documents/Documents.ts | 31 +++++++++++++++- .../CollectionStackingViewFieldColumn.tsx | 8 +++-- .../collections/collectionFreeForm/MarqueeView.tsx | 42 ++++------------------ src/client/views/nodes/DocumentView.tsx | 9 +++-- src/client/views/nodes/FormattedTextBox.tsx | 2 +- src/new_fields/Doc.ts | 16 ++++----- .../authentication/models/current_user_utils.ts | 11 ++---- 7 files changed, 61 insertions(+), 58 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 072e8c612..669aa97b5 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -21,7 +21,7 @@ import { Field, Doc, Opt, DocListCastAsync, FieldResult, DocListCast } from "../ import { ImageField, VideoField, AudioField, PdfField, WebField, YoutubeField } from "../../new_fields/URLField"; import { HtmlField } from "../../new_fields/HtmlField"; import { List } from "../../new_fields/List"; -import { Cast, NumCast } from "../../new_fields/Types"; +import { Cast, NumCast, StrCast } from "../../new_fields/Types"; import { listSpec } from "../../new_fields/Schema"; import { DocServer } from "../DocServer"; import { dropActionType } from "../util/DragManager"; @@ -54,6 +54,8 @@ import { InkingControl } from "../views/InkingControl"; import { RichTextField } from "../../new_fields/RichTextField"; import { extname } from "path"; import { MessageStore } from "../../server/Message"; +import { ContextMenuProps } from "../views/ContextMenuItem"; +import { ContextMenu } from "../views/ContextMenu"; const requestImageSize = require('../util/request-image-size'); const path = require('path'); @@ -898,6 +900,33 @@ export namespace DocUtils { return linkDocProto; } + export function addDocumentCreatorMenuItems(docTextAdder: (d: Doc) => void, docAdder: (d: Doc) => void, x: number, y: number): void { + ContextMenu.Instance.addItem({ + description: "Add Note ...", + subitems: DocListCast((Doc.UserDoc().noteTypes as Doc).data).map((note, i) => ({ + description: ":" + StrCast(note.title), + event: (args: { x: number, y: number }) => docTextAdder(Docs.Create.TextDocument("", { _width: 200, x, y, _autoHeight: true, layout: note, title: StrCast(note.title) + "#" + (note.aliasCount = NumCast(note.aliasCount) + 1) })), + icon: "eye" + })) as ContextMenuProps[], + icon: "eye" + }); + ContextMenu.Instance.addItem({ + description: "Add Template Doc ...", + subitems: DocListCast(Cast(Doc.UserDoc().expandingButtons, Doc, null)?.data).map(btnDoc => Cast(btnDoc?.dragFactory, Doc, null)).filter(doc => doc).map((dragDoc, i) => ({ + description: ":" + StrCast(dragDoc.title), + event: (args: { x: number, y: number }) => { + const newDoc = Doc.ApplyTemplate(dragDoc); + if (newDoc) { + newDoc.x = x; + newDoc.y = y; + docAdder(newDoc); + } + }, + icon: "eye" + })) as ContextMenuProps[], + icon: "eye" + }); + } } Scripting.addGlobal("Docs", Docs); diff --git a/src/client/views/collections/CollectionStackingViewFieldColumn.tsx b/src/client/views/collections/CollectionStackingViewFieldColumn.tsx index 2e3467d90..8c23ecd49 100644 --- a/src/client/views/collections/CollectionStackingViewFieldColumn.tsx +++ b/src/client/views/collections/CollectionStackingViewFieldColumn.tsx @@ -8,10 +8,10 @@ import { Doc, DocListCast } from "../../../new_fields/Doc"; import { RichTextField } from "../../../new_fields/RichTextField"; import { PastelSchemaPalette, SchemaHeaderField } from "../../../new_fields/SchemaHeaderField"; import { ScriptField } from "../../../new_fields/ScriptField"; -import { NumCast, StrCast } from "../../../new_fields/Types"; +import { NumCast, StrCast, Cast } from "../../../new_fields/Types"; import { ImageField } from "../../../new_fields/URLField"; import { TraceMobx } from "../../../new_fields/util"; -import { Docs } from "../../documents/Documents"; +import { Docs, DocUtils } from "../../documents/Documents"; import { DragManager } from "../../util/DragManager"; import { SelectionManager } from "../../util/SelectionManager"; import { Transform } from "../../util/Transform"; @@ -268,8 +268,10 @@ export class CollectionStackingViewFieldColumn extends React.Component dataDoc[fieldKey] instanceof RichTextField || dataDoc[fieldKey] instanceof ImageField || typeof (dataDoc[fieldKey]) === "string").map(fieldKey => docItems.push({ description: ":" + fieldKey, event: () => { diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx index 44109edc5..1db963fa4 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -3,24 +3,20 @@ import { observer } from "mobx-react"; import { Doc, DocListCast } from "../../../../new_fields/Doc"; import { InkField } from "../../../../new_fields/InkField"; import { List } from "../../../../new_fields/List"; -import { listSpec } from "../../../../new_fields/Schema"; import { SchemaHeaderField } from "../../../../new_fields/SchemaHeaderField"; -import { ComputedField } from "../../../../new_fields/ScriptField"; -import { Cast, NumCast, StrCast } from "../../../../new_fields/Types"; +import { Cast, NumCast } from "../../../../new_fields/Types"; import { CurrentUserUtils } from "../../../../server/authentication/models/current_user_utils"; import { Utils } from "../../../../Utils"; -import { Docs } from "../../../documents/Documents"; +import { Docs, DocUtils } from "../../../documents/Documents"; import { SelectionManager } from "../../../util/SelectionManager"; import { Transform } from "../../../util/Transform"; import { undoBatch } from "../../../util/UndoManager"; +import { ContextMenu } from "../../ContextMenu"; import { PreviewCursor } from "../../PreviewCursor"; -import { CollectionViewType } from "../CollectionView"; +import { SubCollectionViewProps } from "../CollectionSubView"; +import MarqueeOptionsMenu from "./MarqueeOptionsMenu"; import "./MarqueeView.scss"; import React = require("react"); -import MarqueeOptionsMenu from "./MarqueeOptionsMenu"; -import { SubCollectionViewProps } from "../CollectionSubView"; -import { ContextMenu } from "../../ContextMenu"; -import { ContextMenuProps } from "../../ContextMenuItem"; interface MarqueeViewProps { getContainerTransform: () => Transform; @@ -69,32 +65,8 @@ export class MarqueeView extends React.Component ({ - description: ":" + StrCast(note.title), - event: (args: { x: number, y: number }) => this.props.addLiveTextDocument(Docs.Create.TextDocument("", { _width: 200, x, y, _autoHeight: true, layout: note, title: StrCast(note.title) + "#" + (note.aliasCount = NumCast(note.aliasCount) + 1) })), - icon: "eye" - })) as ContextMenuProps[], - icon: "eye" - }); - ContextMenu.Instance.addItem({ - description: "Add Template Doc ...", - subitems: DocListCast(Cast(CurrentUserUtils.UserDocument.expandingButtons, Doc, null)?.data).map(btnDoc => Cast(btnDoc?.dragFactory, Doc, null)).filter(doc => doc).map((dragDoc, i) => ({ - description: ":" + StrCast(dragDoc.title), - event: (args: { x: number, y: number }) => { - const newDoc = Doc.ApplyTemplate(dragDoc); - if (newDoc) { - newDoc.x = x; - newDoc.y = y; - this.props.addDocument(newDoc); - } - }, - icon: "eye" - })) as ContextMenuProps[], - icon: "eye" - }); + DocUtils.addDocumentCreatorMenuItems(this.props.addLiveTextDocument, this.props.addDocument, x, y); + ContextMenu.Instance.displayMenu(this._downX, this._downY); } else if (e.key === "q" && e.ctrlKey) { e.preventDefault(); diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 704da3c74..e1d5fcc8a 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -628,6 +628,8 @@ export class DocumentView extends DocComponent(Docu } e.preventDefault(); + const templateDoc = Cast(this.props.Document[StrCast(this.props.Document.layoutKey)], Doc, null); + const cm = ContextMenu.Instance; const subitems: ContextMenuProps[] = []; subitems.push({ description: "Open Full Screen", event: () => CollectionDockingView.Instance && CollectionDockingView.Instance.OpenFullScreen(this, this.props.LibraryPath), icon: "desktop" }); @@ -636,6 +638,7 @@ export class DocumentView extends DocComponent(Docu subitems.push({ description: "Open Alias Tab ", event: () => this.props.addDocTab(Doc.MakeAlias(this.props.Document), this.props.DataDoc, "inTab"), icon: "folder" }); subitems.push({ description: "Open Alias Right", event: () => this.props.addDocTab(Doc.MakeAlias(this.props.Document), this.props.DataDoc, "onRight"), icon: "caret-square-right" }); subitems.push({ description: "Open Fields ", event: () => this.props.addDocTab(Docs.Create.KVPDocument(this.props.Document, { _width: 300, _height: 300 }), undefined, "onRight"), icon: "layer-group" }); + templateDoc && subitems.push({ description: "Open Template ", event: () => this.props.addDocTab(templateDoc, undefined, "onRight"), icon: "eye" }); subitems.push({ description: "Open Repl", icon: "laptop-code", event: () => OverlayView.Instance.addWindow(, { x: 300, y: 100, width: 200, height: 200, title: "Scripting REPL" }) }); cm.addItem({ description: "Open...", subitems: subitems, icon: "external-link-alt" }); @@ -756,7 +759,9 @@ export class DocumentView extends DocComponent(Docu select = (ctrlPressed: boolean) => { SelectionManager.SelectDoc(this, ctrlPressed); }; chromeHeight = () => { - return 1; + const showTitle = StrCast(this.layoutDoc._showTitle); + const showTextTitle = showTitle && (StrCast(this.layoutDoc.layout).indexOf("PresBox") !== -1 || StrCast(this.layoutDoc.layout).indexOf("FormattedTextBox") !== -1) ? showTitle : undefined; + return showTextTitle ? 25 : 1; } @computed get finalLayoutKey() { @@ -857,7 +862,7 @@ export class DocumentView extends DocComponent(Docu this.contents :
    -
    +
    {this.contents}
    {titleView} diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 317f95f81..c1e630e67 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -369,7 +369,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & specificContextMenu = (e: React.MouseEvent): void => { const funcs: ContextMenuProps[] = []; - funcs.push({ description: "Make Template", event: () => { this.props.Document.isTemplateDoc = true; Doc.AddDocToList(Cast(Doc.UserDoc().noteTypes, Doc, null), "data", this.props.Document); }, icon: "eye" }); + !this.props.Document.expandedTemplate && funcs.push({ description: "Make Template", event: () => { this.props.Document.isTemplateDoc = true; Doc.AddDocToList(Cast(Doc.UserDoc().noteTypes, Doc, null), "data", this.props.Document); }, icon: "eye" }); funcs.push({ description: "Toggle Sidebar", event: () => { e.stopPropagation(); this.props.Document._showSidebar = !this.props.Document._showSidebar; }, icon: "expand-arrows-alt" }); funcs.push({ description: "Record Bullet", event: () => { e.stopPropagation(); this.recordBullet(); }, icon: "expand-arrows-alt" }); ["My Text", "Text from Others", "Todo Items", "Important Items", "Ignore Items", "Disagree Items", "By Recent Minute", "By Recent Hour"].forEach(option => diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index 48890ac8d..43bbea623 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -1,22 +1,22 @@ -import { observable, ObservableMap, runInAction, action, computed } from "mobx"; +import { action, computed, observable, ObservableMap, runInAction } from "mobx"; +import { computedFn } from "mobx-utils"; import { alias, map, serializable } from "serializr"; import { DocServer } from "../client/DocServer"; import { DocumentType } from "../client/documents/DocumentTypes"; import { Scripting, scriptingGlobal } from "../client/util/Scripting"; import { afterDocDeserialize, autoObject, Deserializable, SerializationHelper } from "../client/util/SerializationHelper"; -import { Copy, HandleUpdate, Id, OnUpdate, Parent, Self, SelfProxy, ToScriptString, ToString, Update } from "./FieldSymbols"; +import { UndoManager } from "../client/util/UndoManager"; +import { intersectRect } from "../Utils"; +import { HandleUpdate, Id, OnUpdate, Parent, Self, SelfProxy, ToScriptString, ToString, Update } from "./FieldSymbols"; import { List } from "./List"; import { ObjectField } from "./ObjectField"; import { PrefetchProxy, ProxyField } from "./Proxy"; import { FieldId, RefField } from "./RefField"; +import { RichTextField } from "./RichTextField"; import { listSpec } from "./Schema"; -import { ComputedField, ScriptField } from "./ScriptField"; -import { BoolCast, Cast, FieldValue, NumCast, StrCast, ToConstructor } from "./Types"; +import { ComputedField } from "./ScriptField"; +import { Cast, FieldValue, NumCast, StrCast, ToConstructor } from "./Types"; import { deleteProperty, getField, getter, makeEditable, makeReadOnly, setter, updateFunction } from "./util"; -import { intersectRect } from "../Utils"; -import { UndoManager, undoBatch } from "../client/util/UndoManager"; -import { computedFn } from "mobx-utils"; -import { RichTextField } from "./RichTextField"; export namespace Field { export function toKeyValueString(doc: Doc, key: string): string { diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 66d1129f2..e9c12b70c 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -34,30 +34,25 @@ export class CurrentUserUtils { @observable public static GuestWorkspace: Doc | undefined; @observable public static GuestMobile: Doc | undefined; - // a default set of note types .. not being used yet... - static setupNoteTypes(doc: Doc) { - return [ + static setupDefaultDocTemplates(doc: Doc, buttons?: string[]) { + const noteTemplates = [ Docs.Create.TextDocument("", { title: "Note", backgroundColor: "yellow", isTemplateDoc: true }), Docs.Create.TextDocument("", { title: "Idea", backgroundColor: "pink", isTemplateDoc: true }), Docs.Create.TextDocument("", { title: "Topic", backgroundColor: "lightBlue", isTemplateDoc: true }), Docs.Create.TextDocument("", { title: "Person", backgroundColor: "lightGreen", isTemplateDoc: true }), Docs.Create.TextDocument("", { title: "Todo", backgroundColor: "orange", isTemplateDoc: true }) ]; - } - static setupDefaultDocTemplates(doc: Doc, buttons?: string[]) { - doc.noteTypes = new PrefetchProxy(Docs.Create.TreeDocument(CurrentUserUtils.setupNoteTypes(doc), { title: "Note Types", _height: 75 })); + doc.noteTypes = new PrefetchProxy(Docs.Create.TreeDocument(noteTemplates, { title: "Note Types", _height: 75 })); } // setup the "creator" buttons for the sidebar-- eg. the default set of draggable document creation tools static setupCreatorButtons(doc: Doc, buttons?: string[]) { - const notes = DocListCast(Cast(doc.noteTypes, Doc, null)?.data); const emptyPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation", _viewType: CollectionViewType.Stacking, _LODdisable: true, _chromeStatus: "replaced", _showTitle: "title", boxShadow: "0 0" }); const emptyCollection = Docs.Create.FreeformDocument([], { _nativeWidth: undefined, _nativeHeight: undefined, _LODdisable: true, _width: 150, _height: 100, title: "freeform" }); doc.activePen = doc; const docProtoData: { title: string, icon: string, drag?: string, ignoreClick?: boolean, click?: string, ischecked?: string, activePen?: Doc, backgroundColor?: string, dragFactory?: Doc }[] = [ { title: "collection", icon: "folder", click: 'openOnRight(getCopy(this.dragFactory, true))', drag: 'getCopy(this.dragFactory, true)', dragFactory: emptyCollection }, { title: "preview", icon: "expand", ignoreClick: true, drag: 'Docs.Create.DocumentDocument(ComputedField.MakeFunction("selectedDocs(this,true,[_last_])?.[0]"), { _width: 250, _height: 250, title: "container" })' }, - { title: "todo item", icon: "check", ignoreClick: true, drag: 'getCopy(this.dragFactory, true)', dragFactory: notes[notes.length - 1] }, { title: "web page", icon: "globe-asia", ignoreClick: true, drag: 'Docs.Create.WebDocument("https://en.wikipedia.org/wiki/Hedgehog", {_width: 300, _height: 300, title: "New Webpage" })' }, { title: "cat image", icon: "cat", ignoreClick: true, drag: 'Docs.Create.ImageDocument("https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg", { _width: 200, title: "an image of a cat" })' }, { title: "buxton", icon: "cloud-upload-alt", ignoreClick: true, drag: "Docs.Create.Buxton()" }, -- cgit v1.2.3-70-g09d2 From e625ff09a94160e28f0afda56f4ae7e48b58c0b3 Mon Sep 17 00:00:00 2001 From: bob Date: Wed, 19 Feb 2020 19:02:10 -0500 Subject: enabled multicolumn document to show contents of original document if its a template and no fields are specified ... probably will reverse this later --- .../collectionMulticolumn/CollectionMulticolumnView.tsx | 11 ++++++++--- src/server/authentication/models/current_user_utils.ts | 4 ++-- 2 files changed, 10 insertions(+), 5 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx b/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx index 785f90212..82175c0b5 100644 --- a/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx +++ b/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx @@ -4,7 +4,7 @@ import * as React from "react"; import { Doc } from '../../../../new_fields/Doc'; import { documentSchema } from '../../../../new_fields/documentSchemas'; import { makeInterface } from '../../../../new_fields/Schema'; -import { BoolCast, NumCast, ScriptCast, StrCast } from '../../../../new_fields/Types'; +import { BoolCast, NumCast, ScriptCast, StrCast, Cast } from '../../../../new_fields/Types'; import { DragManager } from '../../../util/DragManager'; import { Transform } from '../../../util/Transform'; import { undoBatch } from '../../../util/UndoManager'; @@ -13,6 +13,7 @@ import { CollectionSubView } from '../CollectionSubView'; import "./collectionMulticolumnView.scss"; import ResizeBar from './MulticolumnResizer'; import WidthLabel from './MulticolumnWidthLabel'; +import { List } from '../../../../new_fields/List'; type MulticolumnDocument = makeInterface<[typeof documentSchema]>; const MulticolumnDocument = makeInterface(documentSchema); @@ -222,13 +223,17 @@ export class CollectionMulticolumnView extends CollectionSubView(MulticolumnDocu */ @computed private get contents(): JSX.Element[] | null { - const { childLayoutPairs } = this; + // bcz: feels like a hack ... trying to show something useful when there's no list document in the data field of a templated object + const expanded = Cast(this.props.Document.expandedTemplate, Doc, null); + let { childLayoutPairs } = this.dataDoc[this.props.fieldKey] instanceof List || !expanded ? this : { childLayoutPairs: [] } as { childLayoutPairs: { layout: Doc, data: Doc }[] }; + const replaced = !childLayoutPairs.length && !Cast(expanded?.layout, Doc, null) && expanded; + childLayoutPairs = childLayoutPairs.length || !replaced ? childLayoutPairs : [{ layout: replaced, data: replaced }]; const { Document, PanelHeight } = this.props; const collector: JSX.Element[] = []; for (let i = 0; i < childLayoutPairs.length; i++) { const { layout } = childLayoutPairs[i]; const dxf = () => this.lookupIndividualTransform(layout).translate(-NumCast(Document._xMargin), -NumCast(Document._yMargin)); - const width = () => this.lookupPixels(layout); + const width = () => expanded ? this.props.PanelWidth() : this.lookupPixels(layout); const height = () => PanelHeight() - 2 * NumCast(Document._yMargin) - (BoolCast(Document.showWidthLabels) ? 20 : 0); collector.push(
    Date: Fri, 21 Feb 2020 09:32:23 -0500 Subject: fixed link naming and exposed link database (at least for testing) --- src/client/documents/Documents.ts | 16 ++++++++++------ src/client/util/LinkManager.ts | 18 +++++++++--------- src/client/views/DocumentButtonBar.tsx | 5 +++-- src/client/views/GestureOverlay.tsx | 2 +- src/client/views/collections/CollectionTreeView.tsx | 4 ++-- src/client/views/linking/LinkEditor.tsx | 10 +++++----- src/client/views/nodes/DocuLinkBox.tsx | 1 + src/client/views/nodes/DocumentView.tsx | 5 +++-- src/server/authentication/models/current_user_utils.ts | 2 +- 9 files changed, 35 insertions(+), 28 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 9c83a6a9e..4bad24be9 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -119,6 +119,7 @@ export interface DocumentOptions { annotationOn?: Doc; removeDropProperties?: List; // list of properties that should be removed from a document when it is dropped. e.g., a creator button may be forceActive to allow it be dragged, but the forceActive property can be removed from the dropped document dbDoc?: Doc; + linkRelationship?: string; // type of relatinoship a link represents ischecked?: ScriptField; // returns whether a font icon box is checked activePen?: Doc; // which pen document is currently active (used as the radio button state for the 'unhecked' pen tool scripts) onClick?: ScriptField; @@ -225,11 +226,12 @@ export namespace Docs { }], [DocumentType.LINK, { layout: { view: LinkBox, dataField: data }, - options: { _height: 75 } + options: { _height: 150 } }], [DocumentType.LINKDOC, { data: new List(), layout: { view: EmptyBox, dataField: data }, + options: { childDropAction: "alias", title: "LINK DB" } }], [DocumentType.YOUTUBE, { layout: { view: YoutubeBox, dataField: data } @@ -407,7 +409,8 @@ export namespace Docs { Scripting.addGlobal(Buxton); const delegateKeys = ["x", "y", "layoutKey", "_width", "_height", "_panX", "_panY", "_viewType", "_nativeWidth", "_nativeHeight", "dropAction", "childDropAction", "_annotationOn", - "_chromeStatus", "_forceActive", "_autoHeight", "_fitWidth", "_LODdisable", "_itemIndex", "_showSidebar", "_showTitle", "_showCaption", "_showTitleHover", "isButton", "isBackground", "removeDropProperties"]; + "_chromeStatus", "_forceActive", "_autoHeight", "_fitWidth", "_LODdisable", "_itemIndex", "_showSidebar", "_showTitle", "_showCaption", "_showTitleHover", + "isButton", "isBackground", "removeDropProperties", "treeViewOpen"]; /** * This function receives the relevant document prototype and uses @@ -524,7 +527,7 @@ export namespace Docs { } export function LinkDocument(source: { doc: Doc, ctx?: Doc }, target: { doc: Doc, ctx?: Doc }, options: DocumentOptions = {}, id?: string) { - const doc = InstanceFromProto(Prototypes.get(DocumentType.LINK), undefined, { isBackground: true, isButton: true, removeDropProperties: new List(["isBackground", "isButton"]), ...options }); + const doc = InstanceFromProto(Prototypes.get(DocumentType.LINK), undefined, { isButton: true, treeViewHideTitle: true, treeViewOpen: false, removeDropProperties: new List(["isBackground", "isButton"]), ...options }); const linkDocProto = Doc.GetProto(doc); linkDocProto.anchor1 = source.doc; linkDocProto.anchor2 = target.doc; @@ -536,7 +539,7 @@ export namespace Docs { if (linkDocProto.layout_key1 === undefined) { Cast(linkDocProto.proto, Doc, null)!.layout_key1 = DocuLinkBox.LayoutString("anchor1"); Cast(linkDocProto.proto, Doc, null)!.layout_key2 = DocuLinkBox.LayoutString("anchor2"); - Cast(linkDocProto.proto, Doc, null)!.linkBoxExcludedKeys = new List(["treeViewExpandedView", "removeDropProperties", "linkBoxExcludedKeys", "treeViewOpen", "proto", "aliasNumber", "title", "isPrototype", "lastOpened", "creationDate", "author"]); + Cast(linkDocProto.proto, Doc, null)!.linkBoxExcludedKeys = new List(["treeViewExpandedView", "removeDropProperties", "linkBoxExcludedKeys", "treeViewOpen", "proto", "aliasNumber", "isPrototype", "lastOpened", "creationDate", "author"]); Cast(linkDocProto.proto, Doc, null)!.layoutKey = undefined; } @@ -896,12 +899,13 @@ export namespace DocUtils { }); } - export function MakeLink(source: { doc: Doc, ctx?: Doc }, target: { doc: Doc, ctx?: Doc }, title: string = "", description: string = "", id?: string) { + export function MakeLink(source: { doc: Doc, ctx?: Doc }, target: { doc: Doc, ctx?: Doc }, title: string = "", linkRelationship: string = "", id?: string) { const sv = DocumentManager.Instance.getDocumentView(source.doc); if (sv && sv.props.ContainingCollectionDoc === target.doc) return; if (target.doc === CurrentUserUtils.UserDocument) return undefined; - const linkDoc = Docs.Create.LinkDocument(source, target, { title }, id); + const linkDoc = Docs.Create.LinkDocument(source, target, { title, linkRelationship }, id); + Doc.GetProto(linkDoc).title = ComputedField.MakeFunction('this.anchor1.title +" " + (this.linkRelationship||"to") +" " + this.anchor2.title'); Doc.GetProto(source.doc).links = ComputedField.MakeFunction("links(this)"); Doc.GetProto(target.doc).links = ComputedField.MakeFunction("links(this)"); diff --git a/src/client/util/LinkManager.ts b/src/client/util/LinkManager.ts index 1c328c04e..4457f41e2 100644 --- a/src/client/util/LinkManager.ts +++ b/src/client/util/LinkManager.ts @@ -40,7 +40,7 @@ export class LinkManager { public getAllLinks(): Doc[] { const ldoc = LinkManager.Instance.LinkManagerDoc; if (ldoc) { - const docs = DocListCast(ldoc.allLinks); + const docs = DocListCast(ldoc.data); return docs; } return []; @@ -50,7 +50,7 @@ export class LinkManager { const linkList = LinkManager.Instance.getAllLinks(); linkList.push(linkDoc); if (LinkManager.Instance.LinkManagerDoc) { - LinkManager.Instance.LinkManagerDoc.allLinks = new List(linkList); + LinkManager.Instance.LinkManagerDoc.data = new List(linkList); return true; } return false; @@ -62,7 +62,7 @@ export class LinkManager { if (index > -1) { linkList.splice(index, 1); if (LinkManager.Instance.LinkManagerDoc) { - LinkManager.Instance.LinkManagerDoc.allLinks = new List(linkList); + LinkManager.Instance.LinkManagerDoc.data = new List(linkList); return true; } } @@ -136,12 +136,12 @@ export class LinkManager { } } public addGroupToAnchor(linkDoc: Doc, anchor: Doc, groupDoc: Doc, replace: boolean = false) { - linkDoc.title = groupDoc.title; + linkDoc.linkRelationship = groupDoc.linkRelationship; } // removes group doc of given group type only from given anchor on given link public removeGroupFromAnchor(linkDoc: Doc, anchor: Doc, groupType: string) { - linkDoc.title = "-ungrouped-"; + linkDoc.linkRelationship = "-ungrouped-"; } // returns map of group type to anchor's links in that group type @@ -149,9 +149,9 @@ export class LinkManager { const related = this.getAllRelatedLinks(anchor); const anchorGroups = new Map>(); related.forEach(link => { - if (link.title && link.title !== "-ungrouped-") { - const group = anchorGroups.get(StrCast(link.title)); - anchorGroups.set(StrCast(link.title), group ? [...group, link] : [link]); + if (!link.linkRelationship || link?.linkRelationship !== "-ungrouped-") { + const group = anchorGroups.get(StrCast(link.linkRelationship)); + anchorGroups.set(StrCast(link.linkRelationship), group ? [...group, link] : [link]); } else { // if link is in no groups then put it in default group @@ -184,7 +184,7 @@ export class LinkManager { const md: Doc[] = []; const allLinks = LinkManager.Instance.getAllLinks(); allLinks.forEach(linkDoc => { - if (StrCast(linkDoc.title).toUpperCase() === groupType.toUpperCase()) { md.push(linkDoc); } + if (StrCast(linkDoc.linkRelationship).toUpperCase() === groupType.toUpperCase()) { md.push(linkDoc); } }); return md; } diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx index b1cc8f26a..a3d313224 100644 --- a/src/client/views/DocumentButtonBar.tsx +++ b/src/client/views/DocumentButtonBar.tsx @@ -25,6 +25,7 @@ import { DragManager } from '../util/DragManager'; import { MetadataEntryMenu } from './MetadataEntryMenu'; import { CurrentUserUtils } from '../../server/authentication/models/current_user_utils'; import GoogleAuthenticationManager from '../apis/GoogleAuthenticationManager'; +import { ComputedField } from '../../new_fields/ScriptField'; const higflyout = require("@hig/flyout"); export const { anchorPoints } = higflyout; export const Flyout = higflyout.default; @@ -125,8 +126,8 @@ export class DocumentButtonBar extends React.Component<{ views: (DocumentView | const anchor2Title = linkDoc.anchor2 instanceof Doc ? StrCast(linkDoc.anchor2.title) : "-untitled-"; const anchor2Id = linkDoc.anchor2 instanceof Doc ? linkDoc.anchor2[Id] : ""; const text = RichTextMenu.Instance.MakeLinkToSelection(linkDoc[Id], anchor2Title, e.ctrlKey ? "onRight" : "inTab", anchor2Id); - if (linkDoc.anchor2 instanceof Doc) { - proto.title = text === "" ? proto.title : text + " to " + linkDoc.anchor2.title; // TODO open to more descriptive descriptions of following in text link + if (linkDoc.anchor2 instanceof Doc && !proto.title) { + proto.title = Doc.GetProto(linkDoc).title = ComputedField.MakeFunction('this.anchor1.title +" " + (this.linkRelationship||"to") +" " + this.anchor2.title'); } } linkDrag?.end(); diff --git a/src/client/views/GestureOverlay.tsx b/src/client/views/GestureOverlay.tsx index 580c53a37..a8cf8c197 100644 --- a/src/client/views/GestureOverlay.tsx +++ b/src/client/views/GestureOverlay.tsx @@ -333,7 +333,7 @@ export default class GestureOverlay extends Touchable { this._d1 = doc; } else if (this._d1 !== doc && !LinkManager.Instance.doesLinkExist(this._d1, doc)) { - DocUtils.MakeLink({ doc: this._d1 }, { doc: doc }); + DocUtils.MakeLink({ doc: this._d1 }, { doc: doc }, "gestural link"); actionPerformed = true; } }; diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index 15ad49e26..ee64b7d09 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -128,7 +128,7 @@ class TreeView extends React.Component { } @undoBatch delete = () => this.props.deleteDoc(this.props.document); - @undoBatch openRight = () => this.props.addDocTab(this.props.document, "onRight", this.props.libraryPath); + @undoBatch openRight = () => this.props.addDocTab(this.props.containingCollection.childDropAction === "alias" ? Doc.MakeAlias(this.props.document) : this.props.document, "onRight", this.props.libraryPath); @undoBatch indent = () => this.props.addDocument(this.props.document) && this.delete(); @undoBatch move = (doc: Doc, target: Doc | undefined, addDoc: (doc: Doc) => boolean) => { return this.props.document !== target && this.props.deleteDoc(doc) && addDoc(doc); @@ -229,7 +229,7 @@ class TreeView extends React.Component { if (de.complete.linkDragData) { const sourceDoc = de.complete.linkDragData.linkSourceDocument; const destDoc = this.props.document; - DocUtils.MakeLink({ doc: sourceDoc }, { doc: destDoc }); + DocUtils.MakeLink({ doc: sourceDoc }, { doc: destDoc }, "tree drop link"); e.stopPropagation(); } if (de.complete.docDragData) { diff --git a/src/client/views/linking/LinkEditor.tsx b/src/client/views/linking/LinkEditor.tsx index 6cdd11430..913a04d66 100644 --- a/src/client/views/linking/LinkEditor.tsx +++ b/src/client/views/linking/LinkEditor.tsx @@ -206,13 +206,13 @@ export class LinkGroupEditor extends React.Component { constructor(props: LinkGroupEditorProps) { super(props); - const groupMdKeys = LinkManager.Instance.getMetadataKeysInGroup(StrCast(props.groupDoc.title)); + const groupMdKeys = LinkManager.Instance.getMetadataKeysInGroup(StrCast(props.groupDoc.linkRelationship)); groupMdKeys.forEach(key => this._metadataIds.set(key, Utils.GenerateGuid())); } @action setGroupType = (groupType: string): void => { - this.props.groupDoc.title = groupType; + Doc.GetProto(this.props.groupDoc).linkRelationship = groupType; } removeGroupFromLink = (groupType: string): void => { @@ -241,7 +241,7 @@ export class LinkGroupEditor extends React.Component { renderMetadata = (): JSX.Element[] => { const metadata: Array = []; const groupDoc = this.props.groupDoc; - const groupType = StrCast(groupDoc.title); + const groupType = StrCast(groupDoc.linkRelationship); const groupMdKeys = LinkManager.Instance.getMetadataKeysInGroup(groupType); groupMdKeys.forEach((key) => { @@ -254,7 +254,7 @@ export class LinkGroupEditor extends React.Component { } render() { - const groupType = StrCast(this.props.groupDoc.title); + const groupType = StrCast(this.props.groupDoc.linkRelationship); // if ((groupType && LinkManager.Instance.getMetadataKeysInGroup(groupType).length > 0) || groupType === "") { let buttons = ; let addButton = ; @@ -293,7 +293,7 @@ export class LinkEditor extends React.Component { const destination = LinkManager.Instance.getOppositeAnchor(this.props.linkDoc, this.props.sourceDoc); const groups = [this.props.linkDoc].map(groupDoc => { - return ; + return ; }); return !destination ? (null) : ( diff --git a/src/client/views/nodes/DocuLinkBox.tsx b/src/client/views/nodes/DocuLinkBox.tsx index 1983ae529..c4d99456d 100644 --- a/src/client/views/nodes/DocuLinkBox.tsx +++ b/src/client/views/nodes/DocuLinkBox.tsx @@ -67,6 +67,7 @@ export class DocuLinkBox extends DocComponent(Doc const alias = Doc.MakeAlias(this.props.Document); alias.isButton = undefined; alias.isBackground = undefined; + alias.layoutKey = "layout"; this.props.addDocTab(alias, StrCast(this.props.Document.linkOpenLocation, "inTab")); } else { DocumentManager.Instance.FollowLink(this.props.Document, this.props.ContainingCollectionDoc as Doc, document => this.props.addDocTab(document, StrCast(this.props.Document.linkOpenLocation, "inTab")), false); diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 5a358b6d8..84e9b6abb 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -534,7 +534,8 @@ export class DocumentView extends DocComponent(Docu // const docs = await SearchUtil.Search(`data_l:"${destDoc[Id]}"`, true); // const views = docs.map(d => DocumentManager.Instance.getDocumentView(d)).filter(d => d).map(d => d as DocumentView); de.complete.linkDragData.linkSourceDocument !== this.props.Document && - (de.complete.linkDragData.linkDocument = DocUtils.MakeLink({ doc: de.complete.linkDragData.linkSourceDocument }, { doc: this.props.Document, ctx: this.props.ContainingCollectionDoc }, "-ungrouped-")); // TODODO this is where in text links get passed + (de.complete.linkDragData.linkDocument = DocUtils.MakeLink({ doc: de.complete.linkDragData.linkSourceDocument }, + { doc: this.props.Document, ctx: this.props.ContainingCollectionDoc }, `link from ${de.complete.linkDragData.linkSourceDocument.title} to ${this.props.Document.title}`)); // TODODO this is where in text links get passed } } @@ -868,7 +869,7 @@ export class DocumentView extends DocComponent(Docu ; } @computed get ignorePointerEvents() { - return (this.Document.isBackground && !this.isSelected()) || (this.Document.type === DocumentType.INK && InkingControl.Instance.selectedTool !== InkTool.None); + return (this.Document.isBackground && !this.isSelected()) || this.props.layoutKey?.includes("layout_key") || (this.Document.type === DocumentType.INK && InkingControl.Instance.selectedTool !== InkTool.None); } @observable _animate = 0; diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 125780c8e..3bab00bed 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -189,7 +189,7 @@ export class CurrentUserUtils { return Docs.Create.ButtonDocument({ _width: 50, _height: 25, title: "Library", fontSize: 10, letterSpacing: "0px", textTransform: "unset", borderRounding: "5px 5px 0px 0px", boxShadow: "3px 3px 0px rgb(34, 34, 34)", - sourcePanel: Docs.Create.TreeDocument([doc.workspaces as Doc, doc.documents as Doc, doc.recentlyClosed as Doc], { + sourcePanel: Docs.Create.TreeDocument([doc.workspaces as Doc, doc.documents as Doc, Docs.Prototypes.MainLinkDocument(), doc.recentlyClosed as Doc], { title: "Library", _xMargin: 5, _yMargin: 5, _gridGap: 5, forceActive: true, dropAction: "alias", lockedPosition: true, boxShadow: "0 0", }), targetContainer: sidebarContainer, -- cgit v1.2.3-70-g09d2 From ba31e8581df2341db4bbe4077005664da28888e9 Mon Sep 17 00:00:00 2001 From: bob Date: Fri, 21 Feb 2020 15:47:18 -0500 Subject: added a descriptionView template --- src/server/authentication/models/current_user_utils.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 3bab00bed..32439757c 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -18,6 +18,7 @@ import { CollectionViewType } from "../../../client/views/collections/Collection import { makeTemplate } from "../../../client/util/DropConverter"; import { RichTextField } from "../../../new_fields/RichTextField"; import { PrefetchProxy } from "../../../new_fields/Proxy"; +import { FormattedTextBox } from "../../../client/views/nodes/FormattedTextBox"; export class CurrentUserUtils { private static curr_id: string; @@ -237,6 +238,9 @@ export class CurrentUserUtils { ], { _width: 400, _height: 300, title: "slideView", _chromeStatus: "disabled", _xMargin: 3, _yMargin: 3, _autoHeight: false }); slideTemplate.isTemplateDoc = makeTemplate(slideTemplate); + const descriptionTemplate = Docs.Create.TextDocument("", { title: "descriptionView", _height: 100, _showTitle: "title" }); + Doc.GetProto(descriptionTemplate).layout = FormattedTextBox.LayoutString("description"); + descriptionTemplate.isTemplateDoc = makeTemplate(descriptionTemplate); const iconDoc = Docs.Create.TextDocument("", { title: "icon", _width: 150, _height: 30, isTemplateDoc: true, onClick: ScriptField.MakeScript("setNativeView(this)") }); Doc.GetProto(iconDoc).data = new RichTextField('{"doc":{"type":"doc","content":[{"type":"paragraph","attrs":{"align":null,"color":null,"id":null,"indent":null,"inset":null,"lineSpacing":null,"paddingBottom":null,"paddingTop":null},"content":[{"type":"dashField","attrs":{"fieldKey":"title","docid":""}}]}]},"selection":{"type":"text","anchor":2,"head":2},"storedMarks":[]}', ""); @@ -249,10 +253,11 @@ export class CurrentUserUtils { { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onClick: ScriptField.MakeScript("redo()"), removeDropProperties: new List(["dropAction"]), title: "redo button", icon: "redo-alt" }); doc.slidesBtn = Docs.Create.FontIconDocument( { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: slideTemplate, removeDropProperties: new List(["dropAction"]), title: "presentation slide", icon: "sticky-note" }); - doc.expandingButtons = Docs.Create.LinearDocument([doc.undoBtn as Doc, doc.redoBtn as Doc, doc.slidesBtn as Doc], { + doc.descriptionBtn = Docs.Create.FontIconDocument( + { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: descriptionTemplate, removeDropProperties: new List(["dropAction"]), title: "description view", icon: "sticky-note" }); + doc.expandingButtons = Docs.Create.LinearDocument([doc.undoBtn as Doc, doc.redoBtn as Doc, doc.slidesBtn as Doc, doc.descriptionBtn as Doc], { title: "expanding buttons", _gridGap: 5, _xMargin: 5, _yMargin: 5, _height: 42, _width: 100, boxShadow: "0 0", backgroundColor: "black", treeViewPreventOpen: true, forceActive: true, lockedPosition: true, - dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }) }); } -- cgit v1.2.3-70-g09d2 From 1c73798b14bc91e59ab95225b341008271d0159a Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Sat, 22 Feb 2020 01:04:55 -0500 Subject: removed LinkFollow box. --- src/client/documents/DocumentTypes.ts | 1 - src/client/documents/Documents.ts | 8 - src/client/views/OverlayView.tsx | 2 +- .../views/collections/CollectionLinearView.tsx | 2 +- .../views/collections/CollectionStackingView.tsx | 2 +- .../views/collections/CollectionTreeView.tsx | 1 - .../collectionFreeForm/CollectionFreeFormView.tsx | 6 +- src/client/views/linking/LinkFollowBox.scss | 93 ---- src/client/views/linking/LinkFollowBox.tsx | 571 --------------------- src/client/views/linking/LinkMenuItem.tsx | 1 - src/client/views/nodes/DocumentContentsView.tsx | 3 +- .../authentication/models/current_user_utils.ts | 2 - 12 files changed, 7 insertions(+), 685 deletions(-) delete mode 100644 src/client/views/linking/LinkFollowBox.scss delete mode 100644 src/client/views/linking/LinkFollowBox.tsx (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/documents/DocumentTypes.ts b/src/client/documents/DocumentTypes.ts index 0e6b59b33..06b15d78c 100644 --- a/src/client/documents/DocumentTypes.ts +++ b/src/client/documents/DocumentTypes.ts @@ -19,7 +19,6 @@ export enum DocumentType { WEBCAM = "webcam", FONTICON = "fonticonbox", PRES = "presentation", - LINKFOLLOW = "linkfollow", PRESELEMENT = "preselement", QUERY = "search", COLOR = "color", diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index aed14e4f6..ff64489bb 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -40,7 +40,6 @@ import { PresBox } from "../views/nodes/PresBox"; import { ComputedField, ScriptField } from "../../new_fields/ScriptField"; import { ProxyField } from "../../new_fields/Proxy"; import { DocumentType } from "./DocumentTypes"; -import { LinkFollowBox } from "../views/linking/LinkFollowBox"; import { PresElementBox } from "../views/presentationview/PresElementBox"; import { DashWebRTCVideo } from "../views/webcam/DashWebRTCVideo"; import { QueryBox } from "../views/nodes/QueryBox"; @@ -250,9 +249,6 @@ export namespace Docs { layout: { view: FontIconBox, dataField: data }, options: { _width: 40, _height: 40, borderRounding: "100%" }, }], - [DocumentType.LINKFOLLOW, { - layout: { view: LinkFollowBox, dataField: data } - }], [DocumentType.WEBCAM, { layout: { view: DashWebRTCVideo, dataField: data } }], @@ -658,10 +654,6 @@ export namespace Docs { return InstanceFromProto(Prototypes.get(DocumentType.FONTICON), undefined, { ...(options || {}) }); } - export function LinkFollowBoxDocument(options?: DocumentOptions) { - return InstanceFromProto(Prototypes.get(DocumentType.LINKFOLLOW), undefined, { ...(options || {}) }); - } - export function PresElementBoxDocument(options?: DocumentOptions) { return InstanceFromProto(Prototypes.get(DocumentType.PRESELEMENT), undefined, { ...(options || {}) }); } diff --git a/src/client/views/OverlayView.tsx b/src/client/views/OverlayView.tsx index 7a99bf0ae..220efd4a8 100644 --- a/src/client/views/OverlayView.tsx +++ b/src/client/views/OverlayView.tsx @@ -169,7 +169,7 @@ export class OverlayView extends React.Component { document.addEventListener("pointermove", onPointerMove); document.addEventListener("pointerup", onPointerUp); }; - return
    + return
    NumCast(this.props.Document._height); // 2 * the padding getTransform = (ele: React.RefObject) => () => { diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index 0d5d3e449..a1cc21319 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -38,7 +38,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { @observable _scroll = 0; // used to force the document decoration to update when scrolling @computed get sectionHeaders() { return Cast(this.props.Document.sectionHeaders, listSpec(SchemaHeaderField)); } @computed get sectionFilter() { return StrCast(this.props.Document.sectionFilter); } - @computed get filteredChildren() { return this.childLayoutPairs.filter(pair => pair.layout instanceof Doc && !pair.layout.isMinimized).map(pair => pair.layout); } + @computed get filteredChildren() { return this.childLayoutPairs.filter(pair => pair.layout instanceof Doc).map(pair => pair.layout); } @computed get xMargin() { return NumCast(this.props.Document._xMargin, 2 * Math.min(this.gridGap, .05 * this.props.PanelWidth())); } @computed get yMargin() { return Math.max(this.props.Document._showTitle && !this.props.Document._showTitleHover ? 30 : 0, NumCast(this.props.Document._yMargin, 0)); } // 2 * this.gridGap)); } @computed get gridGap() { return NumCast(this.props.Document._gridGap, 10); } diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index ed1d674c6..7eeeb6ff1 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -421,7 +421,6 @@ class TreeView extends React.Component { return <>
    DocumentManager.Instance.getDocumentView(doc)).map(dv => dv && SelectionManager.SelectDoc(dv, true)); } - public isCurrent(doc: Doc) { return !doc.isMinimized && (Math.abs(NumCast(doc.displayTimecode, -1) - NumCast(this.Document.currentTimecode, -1)) < 1.5 || NumCast(doc.displayTimecode, -1) === -1); } + public isCurrent(doc: Doc) { return (Math.abs(NumCast(doc.displayTimecode, -1) - NumCast(this.Document.currentTimecode, -1)) < 1.5 || NumCast(doc.displayTimecode, -1) === -1); } public getActiveDocuments = () => { return this.childLayoutPairs.filter(pair => this.isCurrent(pair.layout)).map(pair => pair.layout); @@ -433,7 +433,7 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { let x = this.Document._panX || 0; let y = this.Document._panY || 0; - const docs = this.childLayoutPairs.filter(pair => pair.layout instanceof Doc && !pair.layout.isMinimized).map(pair => pair.layout); + const docs = this.childLayoutPairs.filter(pair => pair.layout instanceof Doc).map(pair => pair.layout); const [dx, dy] = this.getTransform().transformDirection(e.clientX - this._lastX, e.clientY - this._lastY); if (!this.isAnnotationOverlay && docs.length && this.childDataProvider(docs[0])) { PDFMenu.Instance.fadeOut(true); @@ -869,7 +869,7 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { })); this._cachedPool.clear(); Array.from(newPool.keys()).forEach(k => this._cachedPool.set(k, newPool.get(k))); - const elements:ViewDefResult[] = computedElementData.slice(); + const elements: ViewDefResult[] = computedElementData.slice(); this.childLayoutPairs.filter(pair => this.isCurrent(pair.layout)).forEach(pair => elements.push({ ele: { - - public static LayoutString(fieldKey: string) { return FieldView.LayoutString(LinkFollowBox, fieldKey); } - public static Instance: LinkFollowBox | undefined; - @observable static linkDoc: Doc | undefined = undefined; - @observable static destinationDoc: Doc | undefined = undefined; - @observable static sourceDoc: Doc | undefined = undefined; - @observable selectedMode: string = ""; - @observable selectedContext: Doc | undefined = undefined; - @observable selectedContextAliases: Doc[] | undefined = undefined; - @observable selectedOption: string = ""; - @observable selectedContextString: string = ""; - @observable sourceView: DocumentView | undefined = undefined; - @observable canPan: boolean = false; - @observable shouldUseOnlyParentContext = false; - _contextDisposer?: IReactionDisposer; - - @observable private _docs: { col: Doc, target: Doc }[] = []; - @observable private _otherDocs: { col: Doc, target: Doc }[] = []; - - constructor(props: FieldViewProps) { - super(props); - LinkFollowBox.Instance = this; - this.resetVars(); - this.props.Document.isBackground = true; - } - - componentDidMount = () => { - this.resetVars(); - - this._contextDisposer = reaction( - () => this.selectedContextString, - async () => { - const ref = await DocServer.GetRefField(this.selectedContextString); - runInAction(() => { - if (ref instanceof Doc) { - this.selectedContext = ref; - } - }); - if (this.selectedContext instanceof Doc) { - const aliases = await SearchUtil.GetViewsOfDocument(this.selectedContext); - runInAction(() => { this.selectedContextAliases = aliases; }); - } - } - ); - } - - componentWillUnmount = () => { - this._contextDisposer && this._contextDisposer(); - } - - async resetPan() { - if (LinkFollowBox.destinationDoc && this.sourceView && this.sourceView.props.ContainingCollectionDoc) { - runInAction(() => this.canPan = false); - if (this.sourceView.props.ContainingCollectionDoc._viewType === CollectionViewType.Freeform) { - const docs = Cast(this.sourceView.props.ContainingCollectionDoc.data, listSpec(Doc), []); - const aliases = await SearchUtil.GetViewsOfDocument(Doc.GetProto(LinkFollowBox.destinationDoc)); - - aliases.forEach(alias => { - if (docs.filter(doc => doc === alias).length > 0) { - runInAction(() => { this.canPan = true; }); - } - }); - } - } - } - - @action - resetVars = () => { - this.selectedContext = undefined; - this.selectedContextString = ""; - this.selectedMode = ""; - this.selectedOption = ""; - LinkFollowBox.linkDoc = undefined; - LinkFollowBox.sourceDoc = undefined; - LinkFollowBox.destinationDoc = undefined; - this.sourceView = undefined; - this.canPan = false; - this.shouldUseOnlyParentContext = false; - } - - async fetchDocuments() { - if (LinkFollowBox.destinationDoc) { - const dest: Doc = LinkFollowBox.destinationDoc; - const aliases = await SearchUtil.GetViewsOfDocument(Doc.GetProto(dest)); - const { docs } = await SearchUtil.Search("", true, { fq: `data_l:"${dest[Id]}"` }); - const map: Map = new Map; - const allDocs = await Promise.all(aliases.map(doc => SearchUtil.Search("", true, { fq: `data_l:"${doc[Id]}"` }).then(result => result.docs))); - allDocs.forEach((docs, index) => docs.forEach(doc => map.set(doc, aliases[index]))); - docs.forEach(doc => map.delete(doc)); - runInAction(async () => { - this._docs = docs.filter(doc => !Doc.AreProtosEqual(doc, CollectionDockingView.Instance.props.Document)).map(doc => ({ col: doc, target: dest })); - this._otherDocs = Array.from(map.entries()).filter(entry => !Doc.AreProtosEqual(entry[0], CollectionDockingView.Instance.props.Document)).map(([col, target]) => ({ col, target })); - const tcontext = LinkFollowBox.linkDoc && (await Cast(LinkFollowBox.linkDoc.anchor2Context, Doc)) as Doc; - runInAction(() => tcontext && this._docs.splice(0, 0, { col: tcontext, target: dest })); - }); - } - } - - @action - setLinkDocs = (linkDoc: Doc, source: Doc, dest: Doc) => { - this.resetVars(); - - LinkFollowBox.linkDoc = linkDoc; - LinkFollowBox.sourceDoc = source; - LinkFollowBox.destinationDoc = dest; - this.fetchDocuments(); - - SelectionManager.SelectedDocuments().forEach(dv => { - if (dv.props.Document === LinkFollowBox.sourceDoc) { - this.sourceView = dv; - } - }); - - this.resetPan(); - } - - highlightDoc = () => LinkFollowBox.destinationDoc && Doc.linkFollowHighlight(LinkFollowBox.destinationDoc); - - @undoBatch - openFullScreen = () => { - if (LinkFollowBox.destinationDoc) { - const view = DocumentManager.Instance.getDocumentView(LinkFollowBox.destinationDoc); - view && CollectionDockingView.Instance && CollectionDockingView.Instance.OpenFullScreen(view); - } - } - - @undoBatch - openColFullScreen = (options: { context: Doc }) => { - if (LinkFollowBox.destinationDoc) { - if (NumCast(options.context._viewType, CollectionViewType.Invalid) === CollectionViewType.Freeform) { - const newPanX = NumCast(LinkFollowBox.destinationDoc.x) + NumCast(LinkFollowBox.destinationDoc._width) / 2; - const newPanY = NumCast(LinkFollowBox.destinationDoc.y) + NumCast(LinkFollowBox.destinationDoc._height) / 2; - options.context._panX = newPanX; - options.context._panY = newPanY; - } - const view = DocumentManager.Instance.getDocumentView(options.context); - view && CollectionDockingView.Instance && CollectionDockingView.Instance.OpenFullScreen(view); - this.highlightDoc(); - } - } - - // should container be a doc or documentview or what? This one needs work and is more long term - @undoBatch - openInContainer = (options: { container: Doc }) => { - - } - - static _addDocTab: (undefined | ((doc: Doc, where: string) => boolean)); - - static setAddDocTab = (addFunc: (doc: Doc, where: string) => boolean) => { - LinkFollowBox._addDocTab = addFunc; - } - - @undoBatch - openLinkColRight = (options: { context: Doc, shouldZoom: boolean }) => { - if (LinkFollowBox.destinationDoc) { - options.context = Doc.IsPrototype(options.context) ? Doc.MakeDelegate(options.context) : options.context; - if (NumCast(options.context._viewType, CollectionViewType.Invalid) === CollectionViewType.Freeform) { - const newPanX = NumCast(LinkFollowBox.destinationDoc.x) + NumCast(LinkFollowBox.destinationDoc._width) / 2; - const newPanY = NumCast(LinkFollowBox.destinationDoc.y) + NumCast(LinkFollowBox.destinationDoc._height) / 2; - options.context._panX = newPanX; - options.context._panY = newPanY; - } - (LinkFollowBox._addDocTab || this.props.addDocTab)(options.context, "onRight"); - - if (options.shouldZoom) this.jumpToLink({ shouldZoom: options.shouldZoom }); - - this.highlightDoc(); - SelectionManager.DeselectAll(); - } - } - - @undoBatch - openLinkRight = () => { - if (LinkFollowBox.destinationDoc) { - const alias = Doc.MakeAlias(LinkFollowBox.destinationDoc); - (LinkFollowBox._addDocTab || this.props.addDocTab)(alias, "onRight"); - this.highlightDoc(); - SelectionManager.DeselectAll(); - } - - } - - @undoBatch - jumpToLink = async (options: { shouldZoom: boolean }) => { - if (LinkFollowBox.sourceDoc && LinkFollowBox.linkDoc) { - const focus = (document: Doc) => { (LinkFollowBox._addDocTab || this.props.addDocTab)(document, "inTab"); SelectionManager.DeselectAll(); }; - //let focus = (doc: Doc, maxLocation: string) => this.props.focus(docthis.props.focus(LinkFollowBox.destinationDoc, true, 1, () => this.props.addDocTab(doc, maxLocation)); - - DocumentManager.Instance.FollowLink(LinkFollowBox.linkDoc, LinkFollowBox.sourceDoc, focus, options && options.shouldZoom, false, undefined); - } - } - - @undoBatch - openLinkTab = () => { - if (LinkFollowBox.destinationDoc) { - const fullScreenAlias = Doc.MakeAlias(LinkFollowBox.destinationDoc); - // this.prosp.addDocTab is empty -- use the link source's addDocTab - (LinkFollowBox._addDocTab || this.props.addDocTab)(fullScreenAlias, "inTab"); - - this.highlightDoc(); - SelectionManager.DeselectAll(); - } - } - - @undoBatch - openLinkColTab = (options: { context: Doc, shouldZoom: boolean }) => { - if (LinkFollowBox.destinationDoc) { - options.context = Doc.IsPrototype(options.context) ? Doc.MakeDelegate(options.context) : options.context; - if (NumCast(options.context._viewType, CollectionViewType.Invalid) === CollectionViewType.Freeform) { - const newPanX = NumCast(LinkFollowBox.destinationDoc.x) + NumCast(LinkFollowBox.destinationDoc._width) / 2; - const newPanY = NumCast(LinkFollowBox.destinationDoc.y) + NumCast(LinkFollowBox.destinationDoc._height) / 2; - options.context._panX = newPanX; - options.context._panY = newPanY; - } - (LinkFollowBox._addDocTab || this.props.addDocTab)(options.context, "inTab"); - if (options.shouldZoom) this.jumpToLink({ shouldZoom: options.shouldZoom }); - - this.highlightDoc(); - SelectionManager.DeselectAll(); - } - } - - @undoBatch - openLinkInPlace = (options: { shouldZoom: boolean }) => { - - if (LinkFollowBox.destinationDoc && LinkFollowBox.sourceDoc) { - if (this.sourceView && this.sourceView.props.addDocument) { - const destViews = DocumentManager.Instance.getDocumentViews(LinkFollowBox.destinationDoc); - if (!destViews.find(dv => dv.props.ContainingCollectionView === this.sourceView!.props.ContainingCollectionView)) { - const alias = Doc.MakeAlias(LinkFollowBox.destinationDoc); - const y = NumCast(LinkFollowBox.sourceDoc.y); - const x = NumCast(LinkFollowBox.sourceDoc.x); - - const width = NumCast(LinkFollowBox.sourceDoc._width); - const height = NumCast(LinkFollowBox.sourceDoc._height); - - alias.x = x + width + 30; - alias.y = y; - alias._width = width; - alias._height = height; - - this.sourceView.props.addDocument(alias); - } - } - - this.jumpToLink({ shouldZoom: options.shouldZoom }); - - this.highlightDoc(); - SelectionManager.DeselectAll(); - } - } - - //set this to be the default link behavior, can be any of the above - public defaultLinkBehavior: (options?: any) => void = this.jumpToLink; - - @action - currentLinkBehavior = () => { - // this.resetPan(); - if (LinkFollowBox.destinationDoc) { - if (this.selectedContextString === "") { - this.selectedContextString = "self"; - this.selectedContext = LinkFollowBox.destinationDoc; - } - if (this.selectedOption === "") this.selectedOption = FollowOptions.NOZOOM; - const shouldZoom: boolean = this.selectedOption === FollowOptions.NOZOOM ? false : true; - const notOpenInContext: boolean = this.selectedContextString === "self" || this.selectedContextString === LinkFollowBox.destinationDoc[Id]; - - if (this.selectedMode === FollowModes.INPLACE) { - if (shouldZoom !== undefined) this.openLinkInPlace({ shouldZoom: shouldZoom }); - } - else if (this.selectedMode === FollowModes.OPENFULL) { - if (notOpenInContext) this.openFullScreen(); - else this.selectedContext && this.openColFullScreen({ context: this.selectedContext }); - } - else if (this.selectedMode === FollowModes.OPENRIGHT) { - if (notOpenInContext) this.openLinkRight(); - else this.selectedContext && this.openLinkColRight({ context: this.selectedContext, shouldZoom: shouldZoom }); - } - else if (this.selectedMode === FollowModes.OPENTAB) { - if (notOpenInContext) this.openLinkTab(); - else this.selectedContext && this.openLinkColTab({ context: this.selectedContext, shouldZoom: shouldZoom }); - } - else if (this.selectedMode === FollowModes.PAN) { - this.jumpToLink({ shouldZoom: shouldZoom }); - } - else return; - } - } - - @action - handleModeChange = (e: React.ChangeEvent) => { - const target = e.target as HTMLInputElement; - this.selectedMode = target.value; - this.selectedContext = undefined; - this.selectedContextString = ""; - - this.shouldUseOnlyParentContext = (this.selectedMode === FollowModes.INPLACE || this.selectedMode === FollowModes.PAN); - - if (this.shouldUseOnlyParentContext) { - if (this.sourceView && this.sourceView.props.ContainingCollectionDoc) { - this.selectedContext = this.sourceView.props.ContainingCollectionDoc; - this.selectedContextString = (StrCast(this.sourceView.props.ContainingCollectionDoc.title)); - } - } - } - - @action - handleOptionChange = (e: React.ChangeEvent) => { - const target = e.target as HTMLInputElement; - this.selectedOption = target.value; - } - - @action - handleContextChange = (e: React.ChangeEvent) => { - const target = e.target as HTMLInputElement; - this.selectedContextString = target.value; - // selectedContext is updated in reaction - this.selectedOption = ""; - } - - @computed - get canOpenInPlace() { - if (this.sourceView && this.sourceView.props.ContainingCollectionDoc) { - const colDoc = this.sourceView.props.ContainingCollectionDoc; - if (colDoc._viewType === CollectionViewType.Freeform) return true; - } - return false; - } - - @computed - get availableModes() { - return ( -
    -
    -
    -
    -
    -
    -
    - ); - } - - @computed - get parentName() { - if (this.sourceView && this.sourceView.props.ContainingCollectionDoc) { - return this.sourceView.props.ContainingCollectionDoc.title; - } - } - - @computed - get parentID(): string { - if (this.sourceView && this.sourceView.props.ContainingCollectionDoc) { - return StrCast(this.sourceView.props.ContainingCollectionDoc[Id]); - } - return "col"; - } - - @computed - get availableContexts() { - return ( - this.shouldUseOnlyParentContext ? - - : -
    -
    - {[...this._docs, ...this._otherDocs].map(doc => { - if (doc && doc.target && doc.col.title !== "Recently Closed") { - return

    ; - } - })} -
    - ); - } - - @computed - get shouldShowZoom(): boolean { - if (this.selectedMode === FollowModes.OPENFULL) return false; - if (this.shouldUseOnlyParentContext) return true; - if (LinkFollowBox.destinationDoc ? this.selectedContextString === LinkFollowBox.destinationDoc[Id] : "self") return false; - - let contextMatch: boolean = false; - if (this.selectedContextAliases) { - this.selectedContextAliases.forEach(alias => { - if (alias._viewType === CollectionViewType.Freeform) contextMatch = true; - }); - } - if (contextMatch) return true; - - return false; - } - - @computed - get availableOptions() { - if (LinkFollowBox.destinationDoc) { - return ( - this.shouldShowZoom ? -
    -
    -
    -
    - : -
    No Available Options
    - ); - } - return null; - } - - render() { - return ( -
    -
    -
    - {LinkFollowBox.linkDoc ? "Link Title: " + StrCast(LinkFollowBox.linkDoc.title) : "No Link Selected"} -
    this.props.Document.isMinimized = true} className="closeDocument">
    -
    -
    {LinkFollowBox.linkDoc ? - LinkFollowBox.sourceDoc && LinkFollowBox.destinationDoc ? "Source: " + StrCast(LinkFollowBox.sourceDoc.title) + ", Destination: " + StrCast(LinkFollowBox.destinationDoc.title) - : "" : ""}
    -
    -
    -
    -
    Mode
    -
    - {LinkFollowBox.linkDoc ? this.availableModes : "Please select a link to view modes"} -
    -
    -
    -
    Context
    -
    - {this.selectedMode !== "" ? this.availableContexts : "Please select a mode to view contexts"} -
    -
    -
    -
    Options
    -
    - {this.selectedContextString !== "" ? this.availableOptions : "Please select a context to view options"} -
    -
    -
    -
    - -
    - -
    -
    - ); - } -} \ No newline at end of file diff --git a/src/client/views/linking/LinkMenuItem.tsx b/src/client/views/linking/LinkMenuItem.tsx index 376afa64b..5fd6e4630 100644 --- a/src/client/views/linking/LinkMenuItem.tsx +++ b/src/client/views/linking/LinkMenuItem.tsx @@ -8,7 +8,6 @@ import { Cast, StrCast } from '../../../new_fields/Types'; import { DragManager } from '../../util/DragManager'; import { LinkManager } from '../../util/LinkManager'; import { ContextMenu } from '../ContextMenu'; -import { LinkFollowBox } from './LinkFollowBox'; import './LinkMenuItem.scss'; import React = require("react"); import { DocumentManager } from '../../util/DocumentManager'; diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index 73a53f5cc..bfda13eb3 100644 --- a/src/client/views/nodes/DocumentContentsView.tsx +++ b/src/client/views/nodes/DocumentContentsView.tsx @@ -9,7 +9,6 @@ import { CollectionDockingView } from "../collections/CollectionDockingView"; import { CollectionFreeFormView } from "../collections/collectionFreeForm/CollectionFreeFormView"; import { CollectionSchemaView } from "../collections/CollectionSchemaView"; import { CollectionView } from "../collections/CollectionView"; -import { LinkFollowBox } from "../linking/LinkFollowBox"; import { YoutubeBox } from "./../../apis/youtube/YoutubeBox"; import { AudioBox } from "./AudioBox"; import { ButtonBox } from "./ButtonBox"; @@ -108,7 +107,7 @@ export class DocumentContentsView extends React.Component Date: Tue, 25 Feb 2020 00:57:37 -0500 Subject: added optional display templates for metadata field values --- src/client/documents/Documents.ts | 10 ++++--- src/client/util/RichTextSchema.tsx | 32 ++++++++++++++-------- .../views/collections/CollectionDockingView.tsx | 2 +- src/client/views/nodes/DocumentView.tsx | 2 +- src/client/views/nodes/FormattedTextBox.tsx | 4 +-- src/new_fields/Doc.ts | 19 +++++++++---- src/new_fields/RichTextField.ts | 4 +++ .../authentication/models/current_user_utils.ts | 18 ++++++++---- 8 files changed, 60 insertions(+), 31 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index ff64489bb..ff152ec6c 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -97,7 +97,10 @@ export interface DocumentOptions { isTemplateForField?: string; // the field key for which the containing document is a rendering template isTemplateDoc?: boolean; templates?: List; - backgroundColor?: string | ScriptField; + backgroundColor?: string | ScriptField; // background color for data doc + _backgroundColor?: string | ScriptField; // background color for each template layout doc ( overrides backgroundColor ) + color?: string; // foreground color data doc + _color?: string; // foreground color for each template layout doc (overrides color) ignoreClick?: boolean; lockedPosition?: boolean; // lock the x,y coordinates of the document so that it can't be dragged lockedTransform?: boolean; // lock the panx,pany and scale parameters of the document so that it be panned/zoomed @@ -133,7 +136,6 @@ export interface DocumentOptions { sourcePanel?: Doc; // panel to display in 'targetContainer' as the result of a button onClick script targetContainer?: Doc; // document whose proto will be set to 'panel' as the result of a onClick click script strokeWidth?: number; - color?: string; treeViewPreventOpen?: boolean; // ignores the treeViewOpen Doc flag which allows a treeViewItem's expand/collapse state to be independent of other views of the same document in the tree view treeViewHideTitle?: boolean; // whether to hide the title of a tree view treeViewHideHeaderFields?: boolean; // whether to hide the drop down options for tree view items. @@ -405,8 +407,8 @@ export namespace Docs { Scripting.addGlobal(Buxton); const delegateKeys = ["x", "y", "layoutKey", "_width", "_height", "_panX", "_panY", "_viewType", "_nativeWidth", "_nativeHeight", "dropAction", "childDropAction", "_annotationOn", - "_chromeStatus", "_forceActive", "_autoHeight", "_fitWidth", "_LODdisable", "_itemIndex", "_showSidebar", "_showTitle", "_showCaption", "_showTitleHover", - "isButton", "isBackground", "removeDropProperties", "treeViewOpen"]; + "_chromeStatus", "_forceActive", "_autoHeight", "_fitWidth", "_LODdisable", "_itemIndex", "_showSidebar", "_showTitle", "_showCaption", "_showTitleHover", "_backgroundColor", + "_color", "isButton", "isBackground", "removeDropProperties", "treeViewOpen"]; /** * This function receives the relevant document prototype and uses diff --git a/src/client/util/RichTextSchema.tsx b/src/client/util/RichTextSchema.tsx index cfbae5dca..ae3f4e731 100644 --- a/src/client/util/RichTextSchema.tsx +++ b/src/client/util/RichTextSchema.tsx @@ -8,7 +8,7 @@ import { EditorState, NodeSelection, Plugin, TextSelection } from "prosemirror-s import { StepMap } from "prosemirror-transform"; import { EditorView } from "prosemirror-view"; import * as ReactDOM from 'react-dom'; -import { Doc, Field, HeightSym, WidthSym } from "../../new_fields/Doc"; +import { Doc, Field, HeightSym, WidthSym, DocListCast } from "../../new_fields/Doc"; import { Id } from "../../new_fields/FieldSymbols"; import { ObjectField } from "../../new_fields/ObjectField"; import { ComputedField } from "../../new_fields/ScriptField"; @@ -850,17 +850,19 @@ export class DashDocView { export class DashFieldView { - _fieldWrapper: HTMLDivElement; - _labelSpan: HTMLSpanElement; - _fieldSpan: HTMLDivElement; + _fieldWrapper: HTMLDivElement; // container for label and value + _labelSpan: HTMLSpanElement; // field label + _fieldSpan: HTMLDivElement; // field value _reactionDisposer: IReactionDisposer | undefined; _textBoxDoc: Doc; @observable _dashDoc: Doc | undefined; _fieldKey: string; + _options: Doc[] = []; constructor(node: any, view: any, getPos: any, tbox: FormattedTextBox) { this._fieldKey = node.attrs.fieldKey; this._textBoxDoc = tbox.props.Document; + this._options = DocListCast(tbox.props.Document[node.attrs.fieldKey + "_options"]); this._fieldWrapper = document.createElement("div"); this._fieldWrapper.style.width = node.attrs.width; this._fieldWrapper.style.height = node.attrs.height; @@ -877,11 +879,15 @@ export class DashFieldView { this._fieldSpan.addEventListener("input", this.onchanged); this._fieldSpan.onkeypress = function (e: any) { e.stopPropagation(); }; this._fieldSpan.onkeyup = function (e: any) { e.stopPropagation(); }; - this._fieldSpan.onmousedown = function (e: any) { - console.log(e); - e.stopPropagation(); - }; + this._fieldSpan.onmousedown = function (e: any) { e.stopPropagation(); }; + const self = this; + const setDashDoc = (doc: Doc) => { + self._dashDoc = doc; + if (this._dashDoc && self._options?.length && !this._dashDoc[node.attrs.fieldKey]) { + this._dashDoc[node.attrs.fieldKey] = StrCast(self._options[0].title); + } + } this._fieldSpan.onkeydown = function (e: any) { e.stopPropagation(); if ((e.key === "a" && e.ctrlKey) || (e.key === "a" && e.metaKey)) { @@ -902,10 +908,9 @@ export class DashFieldView { this._labelSpan.style.fontSize = "larger"; this._labelSpan.innerHTML = `${node.attrs.fieldKey}: `; if (node.attrs.docid) { - const self = this; - DocServer.GetRefField(node.attrs.docid).then(async dashDoc => dashDoc instanceof Doc && runInAction(() => self._dashDoc = dashDoc)); + DocServer.GetRefField(node.attrs.docid).then(async dashDoc => dashDoc instanceof Doc && runInAction(() => setDashDoc(dashDoc))); } else { - this._dashDoc = tbox.props.DataDoc || tbox.dataDoc; + setDashDoc(tbox.props.DataDoc || tbox.dataDoc); } this._reactionDisposer?.(); this._reactionDisposer = reaction(() => this._dashDoc?.[node.attrs.fieldKey], fval => this._fieldSpan.innerHTML = Field.toString(fval as Field) || "(null)", { fireImmediately: true }); @@ -916,7 +921,10 @@ export class DashFieldView { } onchanged = () => { this._reactionDisposer?.(); - this._dashDoc![this._fieldKey] = this._fieldSpan.innerText; + + let newText = this._fieldSpan.innerText; + this._options?.forEach(opt => StrCast(opt.title).startsWith(newText) && (newText = StrCast(opt.title))); + this._dashDoc![this._fieldKey] = newText; this._reactionDisposer = reaction(() => this._dashDoc?.[this._fieldKey], fval => this._fieldSpan.innerHTML = Field.toString(fval as Field) || "(null)"); } diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 83dbb4263..1e38a8927 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -715,7 +715,7 @@ export class DockedFrameRenderer extends React.Component { TraceMobx(); if (!this._document) return (null); const document = this._document; - const resolvedDataDoc = !Doc.AreProtosEqual(this._document[DataSym], this._document) && this._document[DataSym];// document.layout instanceof Doc ? document : this._dataDoc; + const resolvedDataDoc = !Doc.AreProtosEqual(this._document[DataSym], this._document) ? this._document[DataSym] : undefined;// document.layout instanceof Doc ? document : this._dataDoc; return (Docu render() { if (!(this.props.Document instanceof Doc)) return (null); - const backgroundColor = StrCast(this.layoutDoc._backgroundColor) || StrCast(this.layoutDoc.backgroundColor) || this.props.backgroundColor?.(this.Document); + const backgroundColor = StrCast(this.layoutDoc._backgroundColor) || StrCast(this.layoutDoc.backgroundColor) || StrCast(this.Document.backgroundColor) || this.props.backgroundColor?.(this.Document); const fullDegree = Doc.isBrushedHighlightedDegree(this.props.Document); const borderRounding = this.layoutDoc.borderRounding; const localScale = fullDegree; diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index eac495082..5a664f31c 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -192,10 +192,10 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & this.dataDoc[this.props.fieldKey + "-lastModified"] = new DateField(new Date(Date.now())); if (!curTemp || curText) { // if no template, or there's text, write it to the document. (if this is driven by a template, then this overwrites the template text which is intended) this.dataDoc[this.props.fieldKey] = new RichTextField(JSON.stringify(state.toJSON()), curText); - this.dataDoc[this.props.fieldKey + "-noTemplate"] = curTemp?.Text !== curText; + this.dataDoc[this.props.fieldKey + "-noTemplate"] = curTemp?.Text !== curText; // mark the data field as being split from the template if it has been edited } else { // if we've deleted all the text in a note driven by a template, then restore the template data this._editorView.updateState(EditorState.fromJSON(this.config, JSON.parse(curTemp.Data))); - this.dataDoc[this.props.fieldKey + "-noTemplate"] = undefined; + this.dataDoc[this.props.fieldKey + "-noTemplate"] = undefined; // mark the data field as not being split from any template it might have } this._applyingChange = false; } diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index 6142ebb36..10f4309be 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -17,7 +17,6 @@ import { listSpec } from "./Schema"; import { ComputedField } from "./ScriptField"; import { Cast, FieldValue, NumCast, StrCast, ToConstructor } from "./Types"; import { deleteProperty, getField, getter, makeEditable, makeReadOnly, setter, updateFunction } from "./util"; -import { DocumentManager } from "../client/util/DocumentManager"; export namespace Field { export function toKeyValueString(doc: Doc, key: string): string { @@ -612,15 +611,16 @@ export namespace Doc { templateField.isTemplateForField = metadataFieldKey; templateField.title = metadataFieldKey; + const templateFieldValue = templateField[metadataFieldKey]; // move any data that the template field had been rendering over to the template doc so that things will still be rendered // when the template field is adjusted to point to the new metadatafield key. // note 1: if the template field contained a list of documents, each of those documents will be converted to templates as well. // note 2: this will not overwrite any field that already exists on the template doc at the field key - if (!templateDoc?.[metadataFieldKey] && templateField.data instanceof ObjectField) { - Cast(templateField.data, listSpec(Doc), [])?.map(d => d instanceof Doc && MakeMetadataFieldTemplate(d, templateDoc)); - (Doc.GetProto(templateField)[metadataFieldKey] = ObjectField.MakeCopy(templateField.data)); + if (!templateDoc?.[metadataFieldKey] && templateFieldValue instanceof ObjectField) { + Cast(templateFieldValue, listSpec(Doc), [])?.map(d => d instanceof Doc && MakeMetadataFieldTemplate(d, templateDoc)); + (Doc.GetProto(templateField)[metadataFieldKey] = ObjectField.MakeCopy(templateFieldValue)); } - if (templateField.data instanceof RichTextField && (templateField.data.Text || templateField.data.Data.toString().includes("dashField"))) { + if (templateFieldValue instanceof RichTextField && (templateFieldValue.Text || templateFieldValue.Data.toString().includes("dashField"))) { templateField._textTemplate = ComputedField.MakeFunction(`copyField(this.${metadataFieldKey})`, { this: Doc.name }); } @@ -838,6 +838,15 @@ export namespace Doc { DocServer.GetRefField(id).then(layout => layout instanceof Doc && (doc[field] = layout)); return id; } + + export function enumeratedTextTemplate(doc: Doc, layoutString: string, dataKey: string, optionKey: string, modes: Doc[]) { + doc[dataKey] = RichTextField.DashField(optionKey); + doc.layout = layoutString; + const optionsField = `${optionKey}_options`; + doc[optionsField] = new List(modes); + doc.backgroundColor = ComputedField.MakeFunction(`this['${optionsField}'].find(doc => doc.title === this.expandedTemplate.${optionKey})?._backgroundColor || "white"`); + doc.color = ComputedField.MakeFunction(`this['${optionsField}'].find(doc => doc.title === this.expandedTemplate.${optionKey}).color || "black"`); + } } Scripting.addGlobal(function renameAlias(doc: any, n: any) { return StrCast(Doc.GetProto(doc).title).replace(/\([0-9]*\)/, "") + `(${n})`; }); diff --git a/src/new_fields/RichTextField.ts b/src/new_fields/RichTextField.ts index a0f21f45e..712f3e76b 100644 --- a/src/new_fields/RichTextField.ts +++ b/src/new_fields/RichTextField.ts @@ -30,4 +30,8 @@ export class RichTextField extends ObjectField { return this.Text; } + public static DashField(fieldKey:string) { + return new RichTextField(`{"doc":{"type":"doc","content":[{"type":"paragraph","attrs":{"align":null,"color":null,"id":null,"indent":null,"inset":null,"lineSpacing":null,"paddingBottom":null,"paddingTop":null},"content":[{"type":"dashField","attrs":{"fieldKey":"${fieldKey}","docid":""}}]}]},"selection":{"type":"text","anchor":2,"head":2},"storedMarks":[]}`, ""); + } + } \ No newline at end of file diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 8fe2257fc..aaf3a3eb6 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -37,13 +37,19 @@ export class CurrentUserUtils { static setupDefaultDocTemplates(doc: Doc, buttons?: string[]) { const noteTemplates = [ - Docs.Create.TextDocument("", { title: "Note", backgroundColor: "yellow", isTemplateDoc: true }), - Docs.Create.TextDocument("", { title: "Idea", backgroundColor: "pink", isTemplateDoc: true }), - Docs.Create.TextDocument("", { title: "Topic", backgroundColor: "lightBlue", isTemplateDoc: true }), - Docs.Create.TextDocument("", { title: "Person", backgroundColor: "lightGreen", isTemplateDoc: true }), - Docs.Create.TextDocument("", { title: "Todo", backgroundColor: "orange", isTemplateDoc: true }) + Docs.Create.TextDocument("", { title: "Note", backgroundColor: "yellow" }), + Docs.Create.TextDocument("", { title: "Idea", backgroundColor: "pink" }), + Docs.Create.TextDocument("", { title: "Topic", backgroundColor: "lightBlue" }), + Docs.Create.TextDocument("", { title: "Person", backgroundColor: "lightGreen" }), + Docs.Create.TextDocument("", { title: "Todo", backgroundColor: "orange" }) ]; - doc.noteTypes = new PrefetchProxy(Docs.Create.TreeDocument(noteTemplates, { title: "Note Types", _height: 75 })); + const modes = [ + Docs.Create.TextDocument("", { title: "todo", _backgroundColor: "blue", color: "white" }), + Docs.Create.TextDocument("", { title: "in progress", _backgroundColor: "yellow", color: "black" }), + Docs.Create.TextDocument("", { title: "completed", _backgroundColor: "green", color: "white" }) + ] + Doc.enumeratedTextTemplate(Doc.GetProto(noteTemplates[4]), FormattedTextBox.LayoutString("Todo"), "Todo", "taskStatus", modes); + doc.noteTypes = new PrefetchProxy(Docs.Create.TreeDocument(noteTemplates.map(nt => makeTemplate(nt) ? nt : nt), { title: "Note Types", _height: 75 })); } // setup the "creator" buttons for the sidebar-- eg. the default set of draggable document creation tools -- cgit v1.2.3-70-g09d2 From 9399d2a44261ffce3f33cf1ea2dac032a8d3fdc8 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Tue, 25 Feb 2020 02:53:23 -0500 Subject: improved text templates to work better with captions --- src/client/documents/Documents.ts | 3 +-- src/client/util/RichTextSchema.tsx | 2 +- src/client/views/nodes/DocumentView.tsx | 23 ++++++++++++++++++++-- src/client/views/nodes/FormattedTextBox.tsx | 12 +++++------ src/new_fields/Doc.ts | 15 +++++++++----- .../authentication/models/current_user_utils.ts | 4 ++-- 6 files changed, 41 insertions(+), 18 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index ff152ec6c..6d5fd5677 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -77,7 +77,6 @@ export interface DocumentOptions { _gridGap?: number; // gap between items in masonry view _xMargin?: number; // gap between left edge of document and start of masonry/stacking layouts _yMargin?: number; // gap between top edge of dcoument and start of masonry/stacking layouts - _textTemplate?: RichTextField; // template used by a formattedTextBox to create a text box to render _itemIndex?: number; // which item index the carousel viewer is showing _showSidebar?: boolean; //whether an annotationsidebar should be displayed for text docuemnts x?: number; @@ -911,7 +910,7 @@ export namespace DocUtils { description: "Add Note ...", subitems: DocListCast((Doc.UserDoc().noteTypes as Doc).data).map((note, i) => ({ description: ":" + StrCast(note.title), - event: (args: { x: number, y: number }) => docTextAdder(Docs.Create.TextDocument("", { _width: 200, x, y, _autoHeight: true, layout: note, title: StrCast(note.title) + "#" + (note.aliasCount = NumCast(note.aliasCount) + 1) })), + event: (args: { x: number, y: number }) => docTextAdder(Docs.Create.TextDocument("", { _width: 200, x, y, _autoHeight: note._autoHeight !== false, layout: note, title: StrCast(note.title) + "#" + (note.aliasCount = NumCast(note.aliasCount) + 1) })), icon: "eye" })) as ContextMenuProps[], icon: "eye" diff --git a/src/client/util/RichTextSchema.tsx b/src/client/util/RichTextSchema.tsx index ae3f4e731..626d9d75d 100644 --- a/src/client/util/RichTextSchema.tsx +++ b/src/client/util/RichTextSchema.tsx @@ -807,7 +807,7 @@ export class DashDocView { if (finalLayout !== dashDoc && finalKey) { const finalLayoutField = finalLayout[finalKey]; if (finalLayoutField instanceof ObjectField) { - finalLayout._textTemplate = ComputedField.MakeFunction(`copyField(this.${finalKey})`, { this: Doc.name }); + finalLayout[finalKey + "-textTemplate"] = ComputedField.MakeFunction(`copyField(this.${finalKey})`, { this: Doc.name }); } } this._reactionDisposer?.(); diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index aec18ecbb..3660c327a 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -813,6 +813,25 @@ export class DocumentView extends DocComponent(Docu return anchor.type === DocumentType.AUDIO && NumCast(ept) ? false : true; } + // bcz: ARGH! these two are the same as in DocumentContentsView (without the _). They should be reconciled to be the same functions... + get _dataDoc() { + if (this.props.DataDoc === undefined && typeof Doc.LayoutField(this.props.Document) !== "string") { + // if there is no dataDoc (ie, we're not rendering a template layout), but this document has a layout document (not a layout string), + // then we render the layout document as a template and use this document as the data context for the template layout. + const proto = Doc.GetProto(this.props.Document); + return proto instanceof Promise ? undefined : proto; + } + return this.props.DataDoc instanceof Promise ? undefined : this.props.DataDoc; + } + get _layoutDoc() { + if (this.props.LayoutDoc || (this.props.DataDoc === undefined && typeof Doc.LayoutField(this.props.Document) !== "string")) { + // if there is no dataDoc (ie, we're not rendering a template layout), but this document has a layout document (not a layout string), + // then we render the layout document as a template and use this document as the data context for the template layout. + return Doc.expandTemplateLayout(this.props.LayoutDoc?.() || Doc.Layout(this.props.Document), this.props.Document); + } + return Doc.Layout(this.props.Document); + } + @computed get innards() { TraceMobx(); const showTitle = StrCast(this.layoutDoc._showTitle); @@ -825,8 +844,8 @@ export class DocumentView extends DocComponent(Docu
    ); const captionView = (!showCaption ? (null) :
    - diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 5a664f31c..a320cff75 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -186,13 +186,13 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & const tsel = this._editorView.state.selection.$from; tsel.marks().filter(m => m.type === this._editorView!.state.schema.marks.user_mark).map(m => AudioBox.SetScrubTime(Math.max(0, m.attrs.modified * 5000 - 1000))); const curText = state.doc.textBetween(0, state.doc.content.size, "\n\n"); - const curTemp = Cast(this.props.Document._textTemplate, RichTextField); + const curTemp = Cast(this.props.Document[this.props.fieldKey + "-textTemplate"], RichTextField); if (!this._applyingChange) { this._applyingChange = true; this.dataDoc[this.props.fieldKey + "-lastModified"] = new DateField(new Date(Date.now())); if (!curTemp || curText) { // if no template, or there's text, write it to the document. (if this is driven by a template, then this overwrites the template text which is intended) this.dataDoc[this.props.fieldKey] = new RichTextField(JSON.stringify(state.toJSON()), curText); - this.dataDoc[this.props.fieldKey + "-noTemplate"] = curTemp?.Text !== curText; // mark the data field as being split from the template if it has been edited + this.dataDoc[this.props.fieldKey + "-noTemplate"] = (curTemp?.Text || "") !== curText; // mark the data field as being split from the template if it has been edited } else { // if we've deleted all the text in a note driven by a template, then restore the template data this._editorView.updateState(EditorState.fromJSON(this.config, JSON.parse(curTemp.Data))); this.dataDoc[this.props.fieldKey + "-noTemplate"] = undefined; // mark the data field as not being split from any template it might have @@ -504,10 +504,10 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & this._reactionDisposer = reaction( () => { - if (this.dataDoc[this.props.fieldKey + "-noTemplate"] || !this.props.Document._textTemplate) { + if (this.dataDoc[this.props.fieldKey + "-noTemplate"] || !this.props.Document[this.props.fieldKey + "-textTemplate"]) { return Cast(this.dataDoc[this.props.fieldKey], RichTextField, null)?.Data; } - return Cast(this.props.Document._textTemplate, RichTextField, null)?.Data; + return Cast(this.props.Document[this.props.fieldKey + "-textTemplate"], RichTextField, null)?.Data; }, incomingValue => { if (incomingValue !== undefined && this._editorView && !this._applyingChange) { @@ -752,8 +752,8 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & private setupEditor(config: any, fieldKey: string) { const curText = Cast(this.dataDoc[this.props.fieldKey], RichTextField, null); - const useTemplate = !curText?.Text && this.props.Document._textTemplate; - const rtfField = Cast((useTemplate && this.props.Document._textTemplate) || this.dataDoc[fieldKey], RichTextField); + const useTemplate = !curText?.Text && this.props.Document[this.props.fieldKey + "-textTemplate"]; + const rtfField = Cast((useTemplate && this.props.Document[this.props.fieldKey + "-textTemplate"]) || this.dataDoc[fieldKey], RichTextField); if (this.ProseRef) { const self = this; this._editorView?.destroy(); diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index 10f4309be..8e28a1e00 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -47,7 +47,7 @@ export namespace Field { } else if (field instanceof RefField) { return field[ToString](); } - return "(null)"; + return ""; } export function IsField(field: any): field is Field; export function IsField(field: any, includeUndefined: true): field is Field | undefined; @@ -611,7 +611,8 @@ export namespace Doc { templateField.isTemplateForField = metadataFieldKey; templateField.title = metadataFieldKey; - const templateFieldValue = templateField[metadataFieldKey]; + const templateFieldValue = templateField[metadataFieldKey] || templateField.data; + const templateCaptionValue = templateField.caption; // move any data that the template field had been rendering over to the template doc so that things will still be rendered // when the template field is adjusted to point to the new metadatafield key. // note 1: if the template field contained a list of documents, each of those documents will be converted to templates as well. @@ -620,8 +621,11 @@ export namespace Doc { Cast(templateFieldValue, listSpec(Doc), [])?.map(d => d instanceof Doc && MakeMetadataFieldTemplate(d, templateDoc)); (Doc.GetProto(templateField)[metadataFieldKey] = ObjectField.MakeCopy(templateFieldValue)); } + if (templateCaptionValue instanceof RichTextField && (templateCaptionValue.Text || templateCaptionValue.Data.toString().includes("dashField"))) { + templateField["caption-textTemplate"] = ComputedField.MakeFunction(`copyField(this.caption)`, { this: Doc.name }); + } if (templateFieldValue instanceof RichTextField && (templateFieldValue.Text || templateFieldValue.Data.toString().includes("dashField"))) { - templateField._textTemplate = ComputedField.MakeFunction(`copyField(this.${metadataFieldKey})`, { this: Doc.name }); + templateField[metadataFieldKey + "-textTemplate"] = ComputedField.MakeFunction(`copyField(this.${metadataFieldKey})`, { this: Doc.name }); } // get the layout string that the template uses to specify its layout @@ -839,8 +843,9 @@ export namespace Doc { return id; } - export function enumeratedTextTemplate(doc: Doc, layoutString: string, dataKey: string, optionKey: string, modes: Doc[]) { - doc[dataKey] = RichTextField.DashField(optionKey); + export function enumeratedTextTemplate(doc: Doc, layoutString: string, captionKey: string, optionKey: string, modes: Doc[]) { + doc.caption = RichTextField.DashField(optionKey); + doc._showCaption = captionKey; doc.layout = layoutString; const optionsField = `${optionKey}_options`; doc[optionsField] = new List(modes); diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index aaf3a3eb6..36259f513 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -41,14 +41,14 @@ export class CurrentUserUtils { Docs.Create.TextDocument("", { title: "Idea", backgroundColor: "pink" }), Docs.Create.TextDocument("", { title: "Topic", backgroundColor: "lightBlue" }), Docs.Create.TextDocument("", { title: "Person", backgroundColor: "lightGreen" }), - Docs.Create.TextDocument("", { title: "Todo", backgroundColor: "orange" }) + Docs.Create.TextDocument("", { title: "Todo", backgroundColor: "orange", _autoHeight: false, _height: 100, _showCaption: "caption" }) ]; const modes = [ Docs.Create.TextDocument("", { title: "todo", _backgroundColor: "blue", color: "white" }), Docs.Create.TextDocument("", { title: "in progress", _backgroundColor: "yellow", color: "black" }), Docs.Create.TextDocument("", { title: "completed", _backgroundColor: "green", color: "white" }) ] - Doc.enumeratedTextTemplate(Doc.GetProto(noteTemplates[4]), FormattedTextBox.LayoutString("Todo"), "Todo", "taskStatus", modes); + Doc.enumeratedTextTemplate(Doc.GetProto(noteTemplates[4]), FormattedTextBox.LayoutString("Todo"), "caption", "taskStatus", modes); doc.noteTypes = new PrefetchProxy(Docs.Create.TreeDocument(noteTemplates.map(nt => makeTemplate(nt) ? nt : nt), { title: "Note Types", _height: 75 })); } -- cgit v1.2.3-70-g09d2 From 3c48667061fb417e3a7657a1951659d25b453a9f Mon Sep 17 00:00:00 2001 From: bob Date: Thu, 27 Feb 2020 15:10:14 -0500 Subject: streamlined setting enumerations for fields in text boxes. --- src/client/documents/Documents.ts | 8 ++-- src/client/util/RichTextSchema.tsx | 47 +++++++++++++++------- .../views/collections/CollectionTimeView.scss | 4 +- src/new_fields/Doc.ts | 32 +++++++++++---- .../authentication/models/current_user_utils.ts | 15 +++---- 5 files changed, 73 insertions(+), 33 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 6d5fd5677..a0b8a6382 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -622,12 +622,12 @@ export namespace Docs { return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", schemaColumns: new List(schemaColumns), ...options, _viewType: CollectionViewType.Schema }); } - export function TreeDocument(documents: Array, options: DocumentOptions) { - return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", schemaColumns: new List([new SchemaHeaderField("title", "#f1efeb")]), ...options, _viewType: CollectionViewType.Tree }); + export function TreeDocument(documents: Array, options: DocumentOptions, id?: string) { + return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", schemaColumns: new List([new SchemaHeaderField("title", "#f1efeb")]), ...options, _viewType: CollectionViewType.Tree }, id); } - export function StackingDocument(documents: Array, options: DocumentOptions) { - return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", schemaColumns: new List([new SchemaHeaderField("title", "#f1efeb")]), ...options, _viewType: CollectionViewType.Stacking }); + export function StackingDocument(documents: Array, options: DocumentOptions, id?: string) { + return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", schemaColumns: new List([new SchemaHeaderField("title", "#f1efeb")]), ...options, _viewType: CollectionViewType.Stacking }, id); } export function MulticolumnDocument(documents: Array, options: DocumentOptions) { diff --git a/src/client/util/RichTextSchema.tsx b/src/client/util/RichTextSchema.tsx index cc6b035d7..a56aac9b1 100644 --- a/src/client/util/RichTextSchema.tsx +++ b/src/client/util/RichTextSchema.tsx @@ -22,6 +22,10 @@ import ParagraphNodeSpec from "./ParagraphNodeSpec"; import { Transform } from "./Transform"; import React = require("react"); import { CollectionSchemaBooleanCell } from "../views/collections/CollectionSchemaCells"; +import { ContextMenu } from "../views/ContextMenu"; +import { ContextMenuProps } from "../views/ContextMenuItem"; +import { Docs } from "../documents/Documents"; +import { CollectionView } from "../views/collections/CollectionView"; const blockquoteDOM: DOMOutputSpecArray = ["blockquote", 0], hrDOM: DOMOutputSpecArray = ["hr"], preDOM: DOMOutputSpecArray = ["pre", ["code", 0]], brDOM: DOMOutputSpecArray = ["br"], ulDOM: DOMOutputSpecArray = ["ul", 0]; @@ -863,23 +867,13 @@ export class DashFieldView { constructor(node: any, view: any, getPos: any, tbox: FormattedTextBox) { this._fieldKey = node.attrs.fieldKey; this._textBoxDoc = tbox.props.Document; - this._options = DocListCast(tbox.props.Document[node.attrs.fieldKey + "_options"]); this._fieldWrapper = document.createElement("div"); this._fieldWrapper.style.width = node.attrs.width; this._fieldWrapper.style.height = node.attrs.height; this._fieldWrapper.style.position = "relative"; this._fieldWrapper.style.display = "inline-block"; - const onchanged = (e: any) => { - this._reactionDisposer?.(); - let newText = this._fieldSpan.innerText.startsWith(":=") ? ":=-computed-" : this._fieldSpan.innerText; - this._options?.forEach(opt => StrCast(opt.title).startsWith(newText) && (newText = StrCast(opt.title))); - this._dashDoc![this._fieldKey] = newText; - if (newText.startsWith(":=") && this._dashDoc && e.data === null && !e.inputType.includes("delete")) { - Doc.Layout(tbox.props.Document)[this._fieldKey] = ComputedField.MakeFunction(this._fieldSpan.innerText.substring(2)); - } - } - + const self = this; this._fieldSpan = document.createElement("div"); this._fieldSpan.id = Utils.GenerateGuid(); this._fieldSpan.contentEditable = "true"; @@ -887,12 +881,18 @@ export class DashFieldView { this._fieldSpan.style.display = "inline-block"; this._fieldSpan.style.minWidth = "50px"; this._fieldSpan.style.backgroundColor = "rgba(155, 155, 155, 0.24)"; - this._fieldSpan.addEventListener("input", onchanged); this._fieldSpan.onkeypress = function (e: any) { e.stopPropagation(); }; this._fieldSpan.onkeyup = function (e: any) { e.stopPropagation(); }; this._fieldSpan.onmousedown = function (e: any) { e.stopPropagation(); }; + this._fieldSpan.oncontextmenu = function (e: any) { + ContextMenu.Instance.addItem({ + description: "Show Enumeration Templates", event: () => { + e.stopPropagation(); + DocServer.GetRefField(node.attrs.fieldKey).then(collview => collview instanceof Doc && tbox.props.addDocTab(collview, "onRight")); + }, icon: "expand-arrows-alt" + }); + }; - const self = this; const setDashDoc = (doc: Doc) => { self._dashDoc = doc; if (this._dashDoc && self._options?.length && !this._dashDoc[node.attrs.fieldKey]) { @@ -910,6 +910,25 @@ export class DashFieldView { } e.preventDefault(); } + if (e.key === "Enter" && e.ctrlKey) { + Doc.addEnumerationToTextField(self._textBoxDoc, node.attrs.fieldKey, [Docs.Create.TextDocument(self._fieldSpan.innerText, { title: self._fieldSpan.innerText })]); + e.preventDefault(); + } else if (e.key === "Enter") { + e.preventDefault(); + let newText = self._fieldSpan.innerText.startsWith(":=") ? ":=-computed-" : self._fieldSpan.innerText; + // look for a document whose id === the fieldKey being displayed. If there's a match, then that document + // holds the different enumerated values for the field in the titles of its collected documents. + // if there's a partial match from the start of the input text, complete the text --- TODO: make this an auto suggest box and select from a drop down. + + // alternatively, if the text starts with a ':=' then treat it as an expression by making a computed field from its value storing it in the key + DocServer.GetRefField(node.attrs.fieldKey).then(options => { + (options instanceof Doc) && DocListCast(options.data).forEach(opt => StrCast(opt.title).startsWith(newText) && (newText = StrCast(opt.title))); + self._fieldSpan.innerHTML = self._dashDoc![self._fieldKey] = newText; + if (newText.startsWith(":=") && self._dashDoc && e.data === null && !e.inputType.includes("delete")) { + Doc.Layout(tbox.props.Document)[self._fieldKey] = ComputedField.MakeFunction(self._fieldSpan.innerText.substring(2)); + } + }); + } }; this._labelSpan = document.createElement("span"); @@ -924,7 +943,7 @@ export class DashFieldView { setDashDoc(tbox.props.DataDoc || tbox.dataDoc); } this._reactionDisposer?.(); - this._reactionDisposer = reaction(() => { + this._reactionDisposer = reaction(() => { // this reaction will update the displayed text whenever the document's fieldKey's value changes const dashVal = this._dashDoc?.[node.attrs.fieldKey]; return StrCast(dashVal).startsWith(":=") || !dashVal ? Doc.Layout(tbox.props.Document)[this._fieldKey] : dashVal; }, fval => this._fieldSpan.innerHTML = Field.toString(fval as Field) || "(null)", { fireImmediately: true }); diff --git a/src/client/views/collections/CollectionTimeView.scss b/src/client/views/collections/CollectionTimeView.scss index 6ea5e6908..865fc3cd2 100644 --- a/src/client/views/collections/CollectionTimeView.scss +++ b/src/client/views/collections/CollectionTimeView.scss @@ -10,7 +10,6 @@ .collectionTimeView-backBtn { background: green; display: inline; - margin-right: 20px; } .collectionFreeform-customText { @@ -68,6 +67,9 @@ padding: 5px; border: 1px solid black; display:none; + span { + margin-left : 10px; + } } .collectionTimeView-treeView { diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index 8e28a1e00..8ea347ec3 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -17,6 +17,7 @@ import { listSpec } from "./Schema"; import { ComputedField } from "./ScriptField"; import { Cast, FieldValue, NumCast, StrCast, ToConstructor } from "./Types"; import { deleteProperty, getField, getter, makeEditable, makeReadOnly, setter, updateFunction } from "./util"; +import { Docs } from "../client/documents/Documents"; export namespace Field { export function toKeyValueString(doc: Doc, key: string): string { @@ -571,7 +572,7 @@ export namespace Doc { export function ApplyTemplate(templateDoc: Doc) { if (templateDoc) { const applied = ApplyTemplateTo(templateDoc, Doc.MakeDelegate(new Doc()), "layout", templateDoc.title + "(..." + _applyCount++ + ")"); - applied && (Doc.GetProto(applied).layout = applied.layout); + applied && (Doc.GetProto(applied).type = templateDoc.type); return applied; } return undefined; @@ -843,14 +844,31 @@ export namespace Doc { return id; } - export function enumeratedTextTemplate(doc: Doc, layoutString: string, captionKey: string, optionKey: string, modes: Doc[]) { - doc.caption = RichTextField.DashField(optionKey); + // setup a document to use enumerated values for a specified field name: + // doc: text document + // layoutString: species which text field receives the document's main text (e.g., FormattedTextBox.LayoutString("Todo") ) + // enumeratedFieldKey : specifies which enumerated field of the document is displayed in the caption (e.g., taskStatus) + // captionKey: specifies which field holds the caption template (e.g., caption) -- ideally this wouldn't be needed but would be derived from the layoutString's target field key + // + export function enumeratedTextTemplate(doc: Doc, layoutString: string, enumeratedFieldKey: string, enumeratedDocs: Doc[], captionKey: string = "caption") { + doc.caption = RichTextField.DashField(enumeratedFieldKey); doc._showCaption = captionKey; doc.layout = layoutString; - const optionsField = `${optionKey}_options`; - doc[optionsField] = new List(modes); - doc.backgroundColor = ComputedField.MakeFunction(`this['${optionsField}'].find(doc => doc.title === this.expandedTemplate.${optionKey})?._backgroundColor || "white"`); - doc.color = ComputedField.MakeFunction(`this['${optionsField}'].find(doc => doc.title === this.expandedTemplate.${optionKey}).color || "black"`); + + Doc.addEnumerationToTextField(doc, enumeratedFieldKey, enumeratedDocs); + } + + export function addEnumerationToTextField(doc: Doc, enumeratedFieldKey: string, enumeratedDocs: Doc[]) { + DocServer.GetRefField(enumeratedFieldKey).then(optionsCollection => { + if (!(optionsCollection instanceof Doc)) { + optionsCollection = Docs.Create.StackingDocument([], { title: `${enumeratedFieldKey} field set` }, enumeratedFieldKey); + Doc.AddDocToList((Doc.UserDoc().fieldTypes as Doc), "data", optionsCollection as Doc); + } + const options = optionsCollection as Doc; + doc.backgroundColor = ComputedField.MakeFunction(`options.data.find(doc => doc.title === (this.expandedTemplate||this).${enumeratedFieldKey})?._backgroundColor || "white"`, undefined, { options }); + doc.color = ComputedField.MakeFunction(`options.data.find(doc => doc.title === (this.expandedTemplate||this).${enumeratedFieldKey}).color || "black"`, undefined, { options }); + enumeratedDocs.map(enumeratedDoc => !DocListCast(options.data).find(d => d.title === enumeratedDoc.title) && Doc.AddDocToList(options, "data", enumeratedDoc)); + }); } } diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 36259f513..ea19d9da8 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -36,6 +36,11 @@ export class CurrentUserUtils { @observable public static GuestMobile: Doc | undefined; static setupDefaultDocTemplates(doc: Doc, buttons?: string[]) { + const taskStatusValues = [ + Docs.Create.TextDocument("todo", { title: "todo", _backgroundColor: "blue", color: "white" }), + Docs.Create.TextDocument("in progress", { title: "in progress", _backgroundColor: "yellow", color: "black" }), + Docs.Create.TextDocument("completed", { title: "completed", _backgroundColor: "green", color: "white" }) + ]; const noteTemplates = [ Docs.Create.TextDocument("", { title: "Note", backgroundColor: "yellow" }), Docs.Create.TextDocument("", { title: "Idea", backgroundColor: "pink" }), @@ -43,12 +48,8 @@ export class CurrentUserUtils { Docs.Create.TextDocument("", { title: "Person", backgroundColor: "lightGreen" }), Docs.Create.TextDocument("", { title: "Todo", backgroundColor: "orange", _autoHeight: false, _height: 100, _showCaption: "caption" }) ]; - const modes = [ - Docs.Create.TextDocument("", { title: "todo", _backgroundColor: "blue", color: "white" }), - Docs.Create.TextDocument("", { title: "in progress", _backgroundColor: "yellow", color: "black" }), - Docs.Create.TextDocument("", { title: "completed", _backgroundColor: "green", color: "white" }) - ] - Doc.enumeratedTextTemplate(Doc.GetProto(noteTemplates[4]), FormattedTextBox.LayoutString("Todo"), "caption", "taskStatus", modes); + doc.fieldTypes = Docs.Create.TreeDocument([], { title: "field enumerations" }); + Doc.enumeratedTextTemplate(Doc.GetProto(noteTemplates[4]), FormattedTextBox.LayoutString("Todo"), "taskStatus", taskStatusValues); doc.noteTypes = new PrefetchProxy(Docs.Create.TreeDocument(noteTemplates.map(nt => makeTemplate(nt) ? nt : nt), { title: "Note Types", _height: 75 })); } @@ -196,7 +197,7 @@ export class CurrentUserUtils { return Docs.Create.ButtonDocument({ _width: 50, _height: 25, title: "Library", fontSize: 10, letterSpacing: "0px", textTransform: "unset", borderRounding: "5px 5px 0px 0px", boxShadow: "3px 3px 0px rgb(34, 34, 34)", - sourcePanel: Docs.Create.TreeDocument([doc.workspaces as Doc, doc.documents as Doc, Docs.Prototypes.MainLinkDocument(), doc.recentlyClosed as Doc], { + sourcePanel: Docs.Create.TreeDocument([doc.workspaces as Doc, doc.documents as Doc, Docs.Prototypes.MainLinkDocument(), doc, doc.recentlyClosed as Doc], { title: "Library", _xMargin: 5, _yMargin: 5, _gridGap: 5, forceActive: true, dropAction: "alias", lockedPosition: true, boxShadow: "0 0", }), targetContainer: sidebarContainer, -- cgit v1.2.3-70-g09d2 From fc945bcf674efe62aad67be8c1f337cd9b8c83e2 Mon Sep 17 00:00:00 2001 From: bob Date: Fri, 28 Feb 2020 14:59:31 -0500 Subject: fixed stacking view input color. made doc decs more size aware. fixed default note templates to be templates. --- src/client/views/DocumentDecorations.scss | 12 ++++-- src/client/views/DocumentDecorations.tsx | 49 ++++++++++++---------- .../views/collections/CollectionStackingView.scss | 1 - src/client/views/nodes/FormattedTextBox.tsx | 10 +++-- .../authentication/models/current_user_utils.ts | 10 ++--- 5 files changed, 46 insertions(+), 36 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/views/DocumentDecorations.scss b/src/client/views/DocumentDecorations.scss index 202174097..1992c5efa 100644 --- a/src/client/views/DocumentDecorations.scss +++ b/src/client/views/DocumentDecorations.scss @@ -90,6 +90,14 @@ $linkGap : 3px; cursor: ew-resize; } + .documentDecorations-contextMenu { + background: $alt-accent; + width: 25px; + height: calc(100% + 8px); // 8px for the height of the top resizer bar + grid-column-start: 1; + grid-column-end : 2; + pointer-events: all; + } .documentDecorations-title { background: $alt-accent; opacity: 1; @@ -99,10 +107,6 @@ $linkGap : 3px; overflow: hidden; text-align: center; display:flex; - .documentDecorations-contextMenu { - width: 25px; - height: calc(100% + 8px); // 8px for the height of the top resizer bar - } } .publishBox { width: 20px; diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index a01f32152..9c69e6083 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -403,17 +403,21 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> if (SelectionManager.GetIsDragging() || bounds.x === Number.MAX_VALUE || !seldoc || this._hidden || isNaN(bounds.r) || isNaN(bounds.b) || isNaN(bounds.x) || isNaN(bounds.y)) { return (null); } - const minimizeIcon = ( -
    - {/* Currently, this is set to be enabled if there is no ink selected. It might be interesting to think about minimizing ink if it's useful? -syip2*/} - {SelectionManager.SelectedDocuments().length === 1 ? DocumentDecorations.DocumentIcon(StrCast(seldoc.props.Document.layout, "...")) : "..."} -
    ); + const minimal = bounds.r - bounds.x < 100 ? true : false; + const minimizeIcon = minimal ? ( +
    + +
    ) : ( +
    + {/* Currently, this is set to be enabled if there is no ink selected. It might be interesting to think about minimizing ink if it's useful? -syip2*/} + {SelectionManager.SelectedDocuments().length === 1 ? DocumentDecorations.DocumentIcon(StrCast(seldoc.props.Document.layout, "...")) : "..."} +
    ); const titleArea = this._edtingTitle ? <> - this.titleBlur(true)} onChange={action(e => this._accumulatedTitle = e.target.value)} onKeyPress={this.titleEntered} /> -
    { if (!seldoc.props.Document.customTitle) { seldoc.props.Document.customTitle = true; @@ -423,12 +427,12 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> DocUtils.Publish(seldoc.props.Document, this._accumulatedTitle, seldoc.props.addDocument, seldoc.props.removeDocument); })}> -
    +
    } : -
    -
    +
    + {minimal ? (null) :
    -
    +
    } {`${this.selectionTitle}`}
    ; @@ -443,7 +447,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> if (bounds.y > bounds.b) { bounds.y = bounds.b - (this._resizeBorderWidth + this._linkBoxHeight + this._titleHeight); } - return (
    + return (
    }}> {minimizeIcon} {titleArea} -
    +
    e.preventDefault()}>
    + onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}>
    e.preventDefault()}>
    + onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}>
    e.preventDefault()}>
    + onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}>
    e.preventDefault()}>
    + onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}>
    e.preventDefault()}>
    + onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}>
    e.preventDefault()}>
    + onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}>
    e.preventDefault()}>
    + onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}>
    e.preventDefault()}>
    + onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}>
    e.preventDefault()}>
    + onPointerDown={this.onRadiusDown} onContextMenu={(e) => e.preventDefault()}>
    diff --git a/src/client/views/collections/CollectionStackingView.scss b/src/client/views/collections/CollectionStackingView.scss index 8e3919532..bfa5ea278 100644 --- a/src/client/views/collections/CollectionStackingView.scss +++ b/src/client/views/collections/CollectionStackingView.scss @@ -306,7 +306,6 @@ overflow: hidden; margin: auto; width: 90%; - color: lightgrey; overflow: ellipses; .editableView-container-editing-oneLine, diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index b2458ea1d..f74e5f002 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -46,6 +46,7 @@ import { FieldView, FieldViewProps } from "./FieldView"; import "./FormattedTextBox.scss"; import { FormattedTextBoxComment, formattedTextBoxCommentPlugin } from './FormattedTextBoxComment'; import React = require("react"); +import { PrefetchProxy } from '../../../new_fields/Proxy'; library.add(faEdit); library.add(faSmile, faTextHeight, faUpload); @@ -376,12 +377,15 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & toggleSidebar = () => this._sidebarMovement < 5 && (this.props.Document.sidebarWidthPercent = StrCast(this.props.Document.sidebarWidthPercent, "0%") === "0%" ? "25%" : "0%"); - public static DefaultLayout: Doc | string | undefined; + public static get DefaultLayout(): Doc | string | undefined { + return Cast(Doc.UserDoc().defaultTextLayout, Doc, null) || StrCast(Doc.UserDoc().defaultTextLayout, null); + } specificContextMenu = (e: React.MouseEvent): void => { const funcs: ContextMenuProps[] = []; - this.props.Document.isTemplateDoc && funcs.push({ description: "Make Default Layout", event: async () => FormattedTextBox.DefaultLayout = this.props.Document.proto as Doc, icon: "eye" }); - funcs.push({ description: "Reset Default Layout", event: () => FormattedTextBox.DefaultLayout = undefined, icon: "eye" }); + this.props.Document.isTemplateDoc && funcs.push({ description: "Make Default Layout", event: async () => Doc.UserDoc().defaultTextLayout = new PrefetchProxy(this.props.Document.proto as Doc), icon: "eye" }); + funcs.push({ description: "Reset Default Layout", event: () => Doc.UserDoc().defaultTextLayout = undefined, icon: "eye" }); !this.props.Document.expandedTemplate && funcs.push({ description: "Make Template", event: () => { this.props.Document.isTemplateDoc = true; Doc.AddDocToList(Cast(Doc.UserDoc().noteTypes, Doc, null), "data", this.props.Document); }, icon: "eye" }); + funcs.push({ description: "Toggle Single Line", event: () => this.props.Document.singleLine = !this.props.Document.singleLine, icon: "expand-arrows-alt" }); funcs.push({ description: "Toggle Sidebar", event: () => this.props.Document._showSidebar = !this.props.Document._showSidebar, icon: "expand-arrows-alt" }); funcs.push({ description: "Record Bullet", event: () => this.recordBullet(), icon: "expand-arrows-alt" }); funcs.push({ description: "Toggle Menubar", event: () => this.toggleMenubar(), icon: "expand-arrows-alt" }); diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index ea19d9da8..658b9b715 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -42,11 +42,11 @@ export class CurrentUserUtils { Docs.Create.TextDocument("completed", { title: "completed", _backgroundColor: "green", color: "white" }) ]; const noteTemplates = [ - Docs.Create.TextDocument("", { title: "Note", backgroundColor: "yellow" }), - Docs.Create.TextDocument("", { title: "Idea", backgroundColor: "pink" }), - Docs.Create.TextDocument("", { title: "Topic", backgroundColor: "lightBlue" }), - Docs.Create.TextDocument("", { title: "Person", backgroundColor: "lightGreen" }), - Docs.Create.TextDocument("", { title: "Todo", backgroundColor: "orange", _autoHeight: false, _height: 100, _showCaption: "caption" }) + Docs.Create.TextDocument("", { title: "Note", isTemplateDoc: true, backgroundColor: "yellow" }), + Docs.Create.TextDocument("", { title: "Idea", isTemplateDoc: true, backgroundColor: "pink" }), + Docs.Create.TextDocument("", { title: "Topic", isTemplateDoc: true, backgroundColor: "lightBlue" }), + Docs.Create.TextDocument("", { title: "Person", isTemplateDoc: true, backgroundColor: "lightGreen" }), + Docs.Create.TextDocument("", { title: "Todo", isTemplateDoc: true, backgroundColor: "orange", _autoHeight: false, _height: 100, _showCaption: "caption" }) ]; doc.fieldTypes = Docs.Create.TreeDocument([], { title: "field enumerations" }); Doc.enumeratedTextTemplate(Doc.GetProto(noteTemplates[4]), FormattedTextBox.LayoutString("Todo"), "taskStatus", taskStatusValues); -- cgit v1.2.3-70-g09d2 From dbdf81e191107240a62086ebe65d1dc5e3b503c6 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Tue, 3 Mar 2020 00:18:36 -0500 Subject: several fixes to templates (simplified expanding, notes use 'text' field now, collections show documents when their data field is not a list). multicol/row resizers select their doc. --- package-lock.json | 95 +++++++++------------- src/client/documents/Documents.ts | 23 ++++-- src/client/util/DropConverter.ts | 12 ++- src/client/views/collections/CollectionSubView.tsx | 4 +- .../collections/collectionFreeForm/MarqueeView.tsx | 7 +- .../CollectionMulticolumnView.tsx | 9 +- .../collectionMulticolumn/MulticolumnResizer.tsx | 2 + src/client/views/nodes/DocumentContentsView.tsx | 16 +--- src/client/views/nodes/FormattedTextBox.tsx | 2 +- src/new_fields/Doc.ts | 9 +- .../authentication/models/current_user_utils.ts | 15 ++-- 11 files changed, 88 insertions(+), 106 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/package-lock.json b/package-lock.json index 827fb05b8..ef3ecc9f3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -832,7 +832,7 @@ }, "@types/passport": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@types/passport/-/passport-1.0.2.tgz", + "resolved": "https://registry.npmjs.org/@types/passport/-/passport-1.0.0.tgz", "integrity": "sha512-Pf39AYKf8q+YoONym3150cEwfUD66dtwHJWvbeOzKxnA0GZZ/vAXhNWv9vMhKyRQBQZiQyWQnhYBEBlKW6G8wg==", "requires": { "@types/express": "*" @@ -2226,7 +2226,7 @@ }, "util": { "version": "0.10.3", - "resolved": "http://registry.npmjs.org/util/-/util-0.10.3.tgz", + "resolved": "https://registry.npmjs.org/util/-/util-0.10.3.tgz", "integrity": "sha1-evsa/lCAUkZInj23/g7TeTNqwPk=", "dev": true, "requires": { @@ -2846,7 +2846,7 @@ }, "browserify-aes": { "version": "1.2.0", - "resolved": "http://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", + "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", "integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==", "requires": { "buffer-xor": "^1.0.3", @@ -2880,7 +2880,7 @@ }, "browserify-rsa": { "version": "4.0.1", - "resolved": "http://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz", + "resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz", "integrity": "sha1-IeCr+vbyApzy+vsTNWenAdQTVSQ=", "requires": { "bn.js": "^4.1.0", @@ -3051,7 +3051,7 @@ }, "camelcase-keys": { "version": "2.1.0", - "resolved": "http://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz", + "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz", "integrity": "sha1-MIvur/3ygRkFHvodkyITyRuPkuc=", "requires": { "camelcase": "^2.0.0", @@ -3844,7 +3844,7 @@ }, "create-hash": { "version": "1.2.0", - "resolved": "http://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", + "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==", "requires": { "cipher-base": "^1.0.1", @@ -3856,7 +3856,7 @@ }, "create-hmac": { "version": "1.1.7", - "resolved": "http://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz", + "resolved": "https://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz", "integrity": "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==", "requires": { "cipher-base": "^1.0.3", @@ -4398,7 +4398,7 @@ }, "diffie-hellman": { "version": "5.0.3", - "resolved": "http://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz", + "resolved": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz", "integrity": "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==", "requires": { "bn.js": "^4.1.0", @@ -5697,8 +5697,7 @@ }, "ansi-regex": { "version": "2.1.1", - "bundled": true, - "optional": true + "bundled": true }, "aproba": { "version": "1.2.0", @@ -5716,13 +5715,11 @@ }, "balanced-match": { "version": "1.0.0", - "bundled": true, - "optional": true + "bundled": true }, "brace-expansion": { "version": "1.1.11", "bundled": true, - "optional": true, "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -5735,18 +5732,15 @@ }, "code-point-at": { "version": "1.1.0", - "bundled": true, - "optional": true + "bundled": true }, "concat-map": { "version": "0.0.1", - "bundled": true, - "optional": true + "bundled": true }, "console-control-strings": { "version": "1.1.0", - "bundled": true, - "optional": true + "bundled": true }, "core-util-is": { "version": "1.0.2", @@ -5849,8 +5843,7 @@ }, "inherits": { "version": "2.0.4", - "bundled": true, - "optional": true + "bundled": true }, "ini": { "version": "1.3.5", @@ -5860,7 +5853,6 @@ "is-fullwidth-code-point": { "version": "1.0.0", "bundled": true, - "optional": true, "requires": { "number-is-nan": "^1.0.0" } @@ -5873,20 +5865,17 @@ "minimatch": { "version": "3.0.4", "bundled": true, - "optional": true, "requires": { "brace-expansion": "^1.1.7" } }, "minimist": { "version": "0.0.8", - "bundled": true, - "optional": true + "bundled": true }, "minipass": { "version": "2.9.0", "bundled": true, - "optional": true, "requires": { "safe-buffer": "^5.1.2", "yallist": "^3.0.0" @@ -5903,7 +5892,6 @@ "mkdirp": { "version": "0.5.1", "bundled": true, - "optional": true, "requires": { "minimist": "0.0.8" } @@ -5984,8 +5972,7 @@ }, "number-is-nan": { "version": "1.0.1", - "bundled": true, - "optional": true + "bundled": true }, "object-assign": { "version": "4.1.1", @@ -5995,7 +5982,6 @@ "once": { "version": "1.4.0", "bundled": true, - "optional": true, "requires": { "wrappy": "1" } @@ -6071,8 +6057,7 @@ }, "safe-buffer": { "version": "5.1.2", - "bundled": true, - "optional": true + "bundled": true }, "safer-buffer": { "version": "2.1.2", @@ -6102,7 +6087,6 @@ "string-width": { "version": "1.0.2", "bundled": true, - "optional": true, "requires": { "code-point-at": "^1.0.0", "is-fullwidth-code-point": "^1.0.0", @@ -6120,7 +6104,6 @@ "strip-ansi": { "version": "3.0.1", "bundled": true, - "optional": true, "requires": { "ansi-regex": "^2.0.0" } @@ -6159,13 +6142,11 @@ }, "wrappy": { "version": "1.0.2", - "bundled": true, - "optional": true + "bundled": true }, "yallist": { "version": "3.1.1", - "bundled": true, - "optional": true + "bundled": true } } }, @@ -7383,7 +7364,7 @@ }, "is-accessor-descriptor": { "version": "0.1.6", - "resolved": "http://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", "requires": { "kind-of": "^3.0.2" @@ -7438,7 +7419,7 @@ }, "is-data-descriptor": { "version": "0.1.4", - "resolved": "http://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", "requires": { "kind-of": "^3.0.2" @@ -8169,7 +8150,7 @@ }, "load-json-file": { "version": "1.1.0", - "resolved": "http://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", "requires": { "graceful-fs": "^4.1.2", @@ -8506,7 +8487,7 @@ }, "media-typer": { "version": "0.3.0", - "resolved": "http://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=" }, "mem": { @@ -8538,7 +8519,7 @@ }, "meow": { "version": "3.7.0", - "resolved": "http://registry.npmjs.org/meow/-/meow-3.7.0.tgz", + "resolved": "https://registry.npmjs.org/meow/-/meow-3.7.0.tgz", "integrity": "sha1-cstmi0JSKCkKu/qFaJJYcwioAfs=", "requires": { "camelcase-keys": "^2.0.0", @@ -8713,7 +8694,7 @@ }, "mkdirp": { "version": "0.5.1", - "resolved": "http://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", "requires": { "minimist": "0.0.8" @@ -9051,7 +9032,7 @@ }, "next-tick": { "version": "1.0.0", - "resolved": "http://registry.npmjs.org/next-tick/-/next-tick-1.0.0.tgz", + "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.0.0.tgz", "integrity": "sha1-yobR/ogoFpsBICCOPchCS524NCw=" }, "nice-try": { @@ -9134,7 +9115,7 @@ }, "semver": { "version": "5.3.0", - "resolved": "http://registry.npmjs.org/semver/-/semver-5.3.0.tgz", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.3.0.tgz", "integrity": "sha1-myzl094C0XxgEq0yaqa00M9U+U8=" }, "tar": { @@ -12785,7 +12766,7 @@ }, "os-homedir": { "version": "1.0.2", - "resolved": "http://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", + "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", "integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M=" }, "os-locale": { @@ -12798,7 +12779,7 @@ }, "os-tmpdir": { "version": "1.0.2", - "resolved": "http://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=" }, "osenv": { @@ -13038,7 +13019,7 @@ }, "path-is-absolute": { "version": "1.0.1", - "resolved": "http://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" }, "path-is-inside": { @@ -14464,7 +14445,7 @@ }, "readable-stream": { "version": "2.3.6", - "resolved": "http://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", "requires": { "core-util-is": "~1.0.0", @@ -14906,7 +14887,7 @@ }, "safe-regex": { "version": "1.1.0", - "resolved": "http://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", + "resolved": "https://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", "requires": { "ret": "~0.1.10" @@ -15186,7 +15167,7 @@ }, "sha.js": { "version": "2.4.11", - "resolved": "http://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", + "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==", "requires": { "inherits": "^2.0.1", @@ -16048,7 +16029,7 @@ }, "string_decoder": { "version": "1.1.1", - "resolved": "http://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "requires": { "safe-buffer": "~5.1.0" @@ -16078,7 +16059,7 @@ }, "strip-ansi": { "version": "3.0.1", - "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", "requires": { "ansi-regex": "^2.0.0" @@ -16094,7 +16075,7 @@ }, "strip-eof": { "version": "1.0.0", - "resolved": "http://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", + "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=" }, "strip-indent": { @@ -16911,7 +16892,7 @@ }, "tty-browserify": { "version": "0.0.0", - "resolved": "http://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.0.tgz", + "resolved": "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.0.tgz", "integrity": "sha1-oVe6QC2iTpv5V/mqadUk7tQpAaY=", "dev": true }, @@ -18383,7 +18364,7 @@ }, "wrap-ansi": { "version": "2.1.0", - "resolved": "http://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=", "requires": { "string-width": "^1.0.1", diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index abef72f21..4df90ceb8 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -94,6 +94,7 @@ export interface DocumentOptions { layoutKey?: string; type?: string; title?: string; + style?: string; page?: number; scale?: number; isDisplayPanel?: boolean; // whether the panel functions as GoldenLayout "stack" used to display documents @@ -183,7 +184,7 @@ export namespace Docs { const TemplateMap: TemplateMap = new Map([ [DocumentType.TEXT, { - layout: { view: FormattedTextBox, dataField: data }, + layout: { view: FormattedTextBox, dataField: "text" }, options: { _height: 150, _xMargin: 10, _yMargin: 10 } }], [DocumentType.HIST, { @@ -442,7 +443,7 @@ export namespace Docs { * only when creating a DockDocument from the current user's already existing * main document. */ - export function InstanceFromProto(proto: Doc, data: Field | undefined, options: DocumentOptions, delegId?: string) { + export function InstanceFromProto(proto: Doc, data: Field | undefined, options: DocumentOptions, delegId?: string, fieldKey: string = "data") { const { omit: protoProps, extract: delegateProps } = OmitKeys(options, delegateKeys); if (!("author" in protoProps)) { @@ -455,7 +456,7 @@ export namespace Docs { protoProps.isPrototype = true; - const dataDoc = MakeDataDelegate(proto, protoProps, data); + const dataDoc = MakeDataDelegate(proto, protoProps, data, fieldKey); const viewDoc = Doc.MakeDelegate(dataDoc, delegId); AudioBox.ActiveRecordings.map(d => DocUtils.MakeLink({ doc: viewDoc }, { doc: d }, "audio link", "link to audio: " + d.title)); @@ -473,10 +474,10 @@ export namespace Docs { * @param options initial values to apply to this new delegate * @param value the data to store in this new delegate */ - function MakeDataDelegate(proto: Doc, options: DocumentOptions, value?: D) { + function MakeDataDelegate(proto: Doc, options: DocumentOptions, value?: D, fieldKey: string = "data") { const deleg = Doc.MakeDelegate(proto); if (value !== undefined) { - deleg.data = value; + deleg[fieldKey] = value; } return Doc.assign(deleg, options); } @@ -535,7 +536,7 @@ export namespace Docs { } export function TextDocument(text: string, options: DocumentOptions = {}) { - return InstanceFromProto(Prototypes.get(DocumentType.TEXT), text, options); + return InstanceFromProto(Prototypes.get(DocumentType.TEXT), text, options, undefined, "text"); } export function LinkDocument(source: { doc: Doc, ctx?: Doc }, target: { doc: Doc, ctx?: Doc }, options: DocumentOptions = {}, id?: string) { @@ -929,7 +930,15 @@ export namespace DocUtils { description: "Add Note ...", subitems: DocListCast((Doc.UserDoc().noteTypes as Doc).data).map((note, i) => ({ description: ":" + StrCast(note.title), - event: (args: { x: number, y: number }) => docTextAdder(Docs.Create.TextDocument("", { _width: 200, x, y, _autoHeight: note._autoHeight !== false, layout: note, title: StrCast(note.title) + "#" + (note.aliasCount = NumCast(note.aliasCount) + 1) })), + event: (args: { x: number, y: number }) => { + const textDoc = Docs.Create.TextDocument("", { + _width: 200, x, y, _autoHeight: note._autoHeight !== false, + title: StrCast(note.title) + "#" + (note.aliasCount = NumCast(note.aliasCount) + 1) + }); + textDoc.layoutKey = "layout_" + note.title; + textDoc[textDoc.layoutKey] = note; + docTextAdder(textDoc); + }, icon: "eye" })) as ContextMenuProps[], icon: "eye" diff --git a/src/client/util/DropConverter.ts b/src/client/util/DropConverter.ts index 3c7caa60b..393e39687 100644 --- a/src/client/util/DropConverter.ts +++ b/src/client/util/DropConverter.ts @@ -1,5 +1,5 @@ import { DragManager } from "./DragManager"; -import { Doc, DocListCast } from "../../new_fields/Doc"; +import { Doc, DocListCast, Opt } from "../../new_fields/Doc"; import { DocumentType } from "../documents/DocumentTypes"; import { ObjectField } from "../../new_fields/ObjectField"; import { StrCast } from "../../new_fields/Types"; @@ -8,7 +8,12 @@ import { ScriptField, ComputedField } from "../../new_fields/ScriptField"; import { RichTextField } from "../../new_fields/RichTextField"; import { ImageField } from "../../new_fields/URLField"; -export function makeTemplate(doc: Doc, first: boolean = true): boolean { +// +// converts 'doc' into a template that can be used to render other documents. +// the title of doc is used to determine which field is being templated, so +// passing a value for 'rename' allows the doc to be given a meangingful name +// after it has been converted to +export function makeTemplate(doc: Doc, first: boolean = true, rename: Opt = undefined): boolean { const layoutDoc = doc.layout instanceof Doc && doc.layout.isTemplateForField ? doc.layout : doc; const layout = StrCast(layoutDoc.layout).match(/fieldKey={'[^']*'}/)![0]; const fieldKey = layout.replace("fieldKey={'", "").replace(/'}$/, ""); @@ -29,6 +34,7 @@ export function makeTemplate(doc: Doc, first: boolean = true): boolean { any = Doc.MakeMetadataFieldTemplate(layoutDoc, Doc.GetProto(layoutDoc)); } } + rename && (doc.title = rename); return any; } export function convertDropDataToButtons(data: DragManager.DocumentDragData) { @@ -38,7 +44,7 @@ export function convertDropDataToButtons(data: DragManager.DocumentDragData) { if (!doc.onDragStart && !doc.onClick && !doc.isButtonBar) { const layoutDoc = doc.layout instanceof Doc && doc.layout.isTemplateForField ? doc.layout : doc; if (layoutDoc.type === DocumentType.COL || layoutDoc.type === DocumentType.TEXT || layoutDoc.type === DocumentType.IMG) { - makeTemplate(layoutDoc); + !layoutDoc.isTemplateDoc && makeTemplate(layoutDoc); } else { (layoutDoc.layout instanceof Doc) && !data.userDropAction; } diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index aa31d604e..527623ad4 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -113,7 +113,9 @@ export function CollectionSubView(schemaCtor: (doc: Doc) => T) { return Cast(this.dataField, listSpec(Doc)); } get childDocs() { - const docs = DocListCast(this.dataField); + const dfield = this.dataField; + const rawdocs = (dfield instanceof Doc) ? [dfield] : Cast(dfield, listSpec(Doc), this.props.Document.expandedTemplate && !this.props.annotationsKey ? [Cast(this.props.Document.expandedTemplate, Doc, null)] : []); + const docs = rawdocs.filter(d => !(d instanceof Promise)).map(d => d as Doc); const viewSpecScript = Cast(this.props.Document.viewSpecScript, ScriptField); return viewSpecScript ? docs.filter(d => viewSpecScript.script.run({ doc: d }, console.log).result) : docs; } diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx index d4f1a5444..af701347f 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -109,12 +109,7 @@ export class MarqueeView extends React.Component 48 && e.keyCode <= 57) { - const notes = DocListCast((CurrentUserUtils.UserDocument.noteTypes as Doc).data); - const text = Docs.Create.TextDocument("", { _width: 200, _height: 100, x: x, y: y, _autoHeight: true, title: "-typed text-" }); - text.layout = notes[(e.keyCode - 49) % notes.length]; - this.props.addLiveTextDocument(text); - } + } e.stopPropagation(); } //heuristically converts pasted text into a table. diff --git a/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx b/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx index 82175c0b5..bd20781dc 100644 --- a/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx +++ b/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx @@ -223,17 +223,13 @@ export class CollectionMulticolumnView extends CollectionSubView(MulticolumnDocu */ @computed private get contents(): JSX.Element[] | null { - // bcz: feels like a hack ... trying to show something useful when there's no list document in the data field of a templated object - const expanded = Cast(this.props.Document.expandedTemplate, Doc, null); - let { childLayoutPairs } = this.dataDoc[this.props.fieldKey] instanceof List || !expanded ? this : { childLayoutPairs: [] } as { childLayoutPairs: { layout: Doc, data: Doc }[] }; - const replaced = !childLayoutPairs.length && !Cast(expanded?.layout, Doc, null) && expanded; - childLayoutPairs = childLayoutPairs.length || !replaced ? childLayoutPairs : [{ layout: replaced, data: replaced }]; + let { childLayoutPairs } = this; const { Document, PanelHeight } = this.props; const collector: JSX.Element[] = []; for (let i = 0; i < childLayoutPairs.length; i++) { const { layout } = childLayoutPairs[i]; const dxf = () => this.lookupIndividualTransform(layout).translate(-NumCast(Document._xMargin), -NumCast(Document._yMargin)); - const width = () => expanded ? this.props.PanelWidth() : this.lookupPixels(layout); + const width = () => this.lookupPixels(layout); const height = () => PanelHeight() - 2 * NumCast(Document._yMargin) - (BoolCast(Document.showWidthLabels) ? 20 : 0); collector.push(
    void; } const resizerOpacity = 1; @@ -23,6 +24,7 @@ export default class ResizeBar extends React.Component { @action private registerResizing = (e: React.PointerEvent) => { + this.props.select(false); e.stopPropagation(); e.preventDefault(); window.removeEventListener("pointermove", this.onPointerMove); diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index 41478a3c5..dcb6d4a31 100644 --- a/src/client/views/nodes/DocumentContentsView.tsx +++ b/src/client/views/nodes/DocumentContentsView.tsx @@ -73,21 +73,11 @@ export class DocumentContentsView extends React.Component { - if ((this.props.Document.isTemplateForField === "data" || !this.props.Document.isTemplateForField) && // only update the title if the data document's data field is changing + if ((this.props.Document.isTemplateForField === "text" || !this.props.Document.isTemplateForField) && // only update the title if the data document's data field is changing StrCast(this.dataDoc.title).startsWith("-") && this._editorView && !this.Document.customTitle) { const str = this._editorView.state.doc.textContent; const titlestr = str.substr(0, Math.min(40, str.length)); diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index dcd97f079..0f3896055 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -449,12 +449,11 @@ export namespace Doc { } // - // Determines whether the combination of the layoutDoc and dataDoc represents - // a template relationship : there is a dataDoc and it doesn't match the layoutDoc an - // the lyouatDoc's layout is layout string (not a document) + // Determines whether the layout needs to be expanded (as a template). + // template expansion is rquired when the layout is a template doc/field and there's a datadoc which isn't equal to the layout template // export function WillExpandTemplateLayout(layoutDoc: Doc, dataDoc?: Doc) { - return (layoutDoc.isTemplateForField || layoutDoc.isTemplateDoc) && dataDoc && layoutDoc !== dataDoc && !(Doc.LayoutField(layoutDoc) instanceof Doc); + return (layoutDoc.isTemplateForField || layoutDoc.isTemplateDoc) && dataDoc && layoutDoc !== dataDoc; } // @@ -610,7 +609,7 @@ export namespace Doc { export function MakeMetadataFieldTemplate(templateField: Doc, templateDoc: Opt): boolean { // find the metadata field key that this template field doc will display (indicated by its title) - const metadataFieldKey = StrCast(templateField.title).replace(/^-/, ""); + const metadataFieldKey = StrCast(templateField.isTemplateForField) || StrCast(templateField.title).replace(/^-/, ""); // update the original template to mark it as a template templateField.isTemplateForField = metadataFieldKey; diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index dc63f8a89..6216ab7e6 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -43,15 +43,15 @@ export class CurrentUserUtils { Docs.Create.TextDocument("completed", { title: "completed", _backgroundColor: "green", color: "white" }) ]; const noteTemplates = [ - Docs.Create.TextDocument("", { title: "Note", isTemplateDoc: true, backgroundColor: "yellow" }), - Docs.Create.TextDocument("", { title: "Idea", isTemplateDoc: true, backgroundColor: "pink" }), - Docs.Create.TextDocument("", { title: "Topic", isTemplateDoc: true, backgroundColor: "lightBlue" }), - Docs.Create.TextDocument("", { title: "Person", isTemplateDoc: true, backgroundColor: "lightGreen" }), - Docs.Create.TextDocument("", { title: "Todo", isTemplateDoc: true, backgroundColor: "orange", _autoHeight: false, _height: 100, _showCaption: "caption" }) + Docs.Create.TextDocument("", { title: "text", style: "Note", isTemplateDoc: true, backgroundColor: "yellow" }), + Docs.Create.TextDocument("", { title: "text", style: "Idea", isTemplateDoc: true, backgroundColor: "pink" }), + Docs.Create.TextDocument("", { title: "text", style: "Topic", isTemplateDoc: true, backgroundColor: "lightBlue" }), + Docs.Create.TextDocument("", { title: "text", style: "Person", isTemplateDoc: true, backgroundColor: "lightGreen" }), + Docs.Create.TextDocument("", { title: "text", style: "Todo", isTemplateDoc: true, backgroundColor: "orange", _autoHeight: false, _height: 100, _showCaption: "caption" }) ]; doc.fieldTypes = Docs.Create.TreeDocument([], { title: "field enumerations" }); Doc.enumeratedTextTemplate(Doc.GetProto(noteTemplates[4]), FormattedTextBox.LayoutString("Todo"), "taskStatus", taskStatusValues); - doc.noteTypes = new PrefetchProxy(Docs.Create.TreeDocument(noteTemplates.map(nt => makeTemplate(nt) ? nt : nt), { title: "Note Types", _height: 75 })); + doc.noteTypes = new PrefetchProxy(Docs.Create.TreeDocument(noteTemplates.map(nt => makeTemplate(nt, true, StrCast(nt.style)) ? nt : nt), { title: "Note Types", _height: 75 })); } // setup the "creator" buttons for the sidebar-- eg. the default set of draggable document creation tools @@ -285,7 +285,8 @@ export class CurrentUserUtils { { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: slideTemplate, removeDropProperties: new List(["dropAction"]), title: "presentation slide", icon: "sticky-note" }); doc.descriptionBtn = Docs.Create.FontIconDocument( { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: descriptionTemplate, removeDropProperties: new List(["dropAction"]), title: "description view", icon: "sticky-note" }); - doc.expandingButtons = Docs.Create.LinearDocument([doc.undoBtn as Doc, doc.redoBtn as Doc, doc.slidesBtn as Doc, doc.descriptionBtn as Doc], { + doc.expandingButtons = Docs.Create.LinearDocument([doc.undoBtn as Doc, doc.redoBtn as Doc, doc.slidesBtn as Doc, doc.descriptionBtn as Doc, + ...DocListCast(Cast(doc.noteTypes, Doc, null))], { title: "expanding buttons", _gridGap: 5, _xMargin: 5, _yMargin: 5, _height: 42, _width: 100, boxShadow: "0 0", backgroundColor: "black", treeViewPreventOpen: true, forceActive: true, lockedPosition: true, dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }) -- cgit v1.2.3-70-g09d2 From d4fd33ea337b1136344b73b92e9d5494ff94f090 Mon Sep 17 00:00:00 2001 From: bob Date: Tue, 3 Mar 2020 10:49:22 -0500 Subject: fixes to allow navigation from hashtag tag to pivot/schema/stacking views --- src/client/documents/Documents.ts | 2 +- src/client/util/RichTextRules.ts | 10 +++++ src/client/util/RichTextSchema.tsx | 52 +++++++++++++++------- .../collections/CollectionMasonryViewFieldRow.tsx | 12 ++--- .../views/collections/CollectionStackingView.tsx | 30 ++++++------- .../CollectionStackingViewFieldColumn.tsx | 15 +++---- .../views/collections/CollectionViewChromes.scss | 16 +++---- .../views/collections/CollectionViewChromes.tsx | 20 ++++----- .../collectionFreeForm/CollectionFreeFormView.tsx | 24 +++++----- .../authentication/models/current_user_utils.ts | 2 +- 10 files changed, 105 insertions(+), 78 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 4df90ceb8..49e7520f2 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -122,7 +122,7 @@ export interface DocumentOptions { displayTimecode?: number; // the time that a document should be displayed (e.g., time an annotation should be displayed on a video) borderRounding?: string; boxShadow?: string; - sectionFilter?: string; // field key used to determine headings for sections in stacking and masonry views + _pivotField?: string; // field key used to determine headings for sections in stacking, masonry, pivot views schemaColumns?: List; dockingConfig?: string; annotationOn?: Doc; diff --git a/src/client/util/RichTextRules.ts b/src/client/util/RichTextRules.ts index af3b1a81e..70a1a5154 100644 --- a/src/client/util/RichTextRules.ts +++ b/src/client/util/RichTextRules.ts @@ -100,6 +100,16 @@ export class RichTextRules { const fieldView = state.schema.nodes.dashField.create({ fieldKey, docid }); return state.tr.deleteRange(start, end).insert(start, fieldView); }), + // create an inline view of a tag stored under the '#' field + new InputRule( + new RegExp(/#([a-zA-Z_\-0-9]+)\s$/), + (state, match, start, end) => { + const tag = match[1]; + if (!tag) return state.tr; + this.Document[DataSym]["#"] = tag; + const fieldView = state.schema.nodes.dashField.create({ fieldKey: "#" }); + return state.tr.deleteRange(start, end).insert(start, fieldView); + }), // create an inline view of a document {{ : }} // {{:Doc}} => show default view of document {{}} => show layout for this doc {{ : Doc}} => show layout for another doc new InputRule( new RegExp(/\{\{([a-zA-Z_ \-0-9]*)(:[a-zA-Z_ \-0-9]+)?\}\}$/), diff --git a/src/client/util/RichTextSchema.tsx b/src/client/util/RichTextSchema.tsx index b2ee7320a..c67b42766 100644 --- a/src/client/util/RichTextSchema.tsx +++ b/src/client/util/RichTextSchema.tsx @@ -25,7 +25,11 @@ import { CollectionSchemaBooleanCell } from "../views/collections/CollectionSche import { ContextMenu } from "../views/ContextMenu"; import { ContextMenuProps } from "../views/ContextMenuItem"; import { Docs } from "../documents/Documents"; -import { CollectionView } from "../views/collections/CollectionView"; +import { CollectionView, CollectionViewType } from "../views/collections/CollectionView"; +import { toBlob } from "html-to-image"; +import { listSpec } from "../../new_fields/Schema"; +import { List } from "../../new_fields/List"; +import { SchemaHeaderField } from "../../new_fields/SchemaHeaderField"; const blockquoteDOM: DOMOutputSpecArray = ["blockquote", 0], hrDOM: DOMOutputSpecArray = ["hr"], preDOM: DOMOutputSpecArray = ["pre", ["code", 0]], brDOM: DOMOutputSpecArray = ["br"], ulDOM: DOMOutputSpecArray = ["ul", 0]; @@ -880,7 +884,7 @@ export class DashFieldView { this._fieldSpan.contentEditable = "true"; this._fieldSpan.style.position = "relative"; this._fieldSpan.style.display = "inline-block"; - this._fieldSpan.style.minWidth = "50px"; + this._fieldSpan.style.minWidth = "5px"; this._fieldSpan.style.backgroundColor = "rgba(155, 155, 155, 0.24)"; this._fieldSpan.onkeypress = function (e: any) { e.stopPropagation(); }; this._fieldSpan.onkeyup = function (e: any) { e.stopPropagation(); }; @@ -893,6 +897,21 @@ export class DashFieldView { }, icon: "expand-arrows-alt" }); }; + this._fieldSpan.onblur = function (e: any) { + let newText = self._fieldSpan.innerText.startsWith(":=") ? ":=-computed-" : self._fieldSpan.innerText; + // look for a document whose id === the fieldKey being displayed. If there's a match, then that document + // holds the different enumerated values for the field in the titles of its collected documents. + // if there's a partial match from the start of the input text, complete the text --- TODO: make this an auto suggest box and select from a drop down. + + // alternatively, if the text starts with a ':=' then treat it as an expression by making a computed field from its value storing it in the key + DocServer.GetRefField(node.attrs.fieldKey).then(options => { + (options instanceof Doc) && DocListCast(options.data).forEach(opt => StrCast(opt.title).startsWith(newText) && (newText = StrCast(opt.title))); + self._fieldSpan.innerHTML = self._dashDoc![self._fieldKey] = newText; + if (newText.startsWith(":=") && self._dashDoc && e.data === null && !e.inputType.includes("delete")) { + Doc.Layout(tbox.props.Document)[self._fieldKey] = ComputedField.MakeFunction(self._fieldSpan.innerText.substring(2)); + } + }); + } const setDashDoc = (doc: Doc) => { self._dashDoc = doc; @@ -916,19 +935,7 @@ export class DashFieldView { if (e.ctrlKey) { Doc.addEnumerationToTextField(self._textBoxDoc, node.attrs.fieldKey, [Docs.Create.TextDocument(self._fieldSpan.innerText, { title: self._fieldSpan.innerText })]); } - let newText = self._fieldSpan.innerText.startsWith(":=") ? ":=-computed-" : self._fieldSpan.innerText; - // look for a document whose id === the fieldKey being displayed. If there's a match, then that document - // holds the different enumerated values for the field in the titles of its collected documents. - // if there's a partial match from the start of the input text, complete the text --- TODO: make this an auto suggest box and select from a drop down. - - // alternatively, if the text starts with a ':=' then treat it as an expression by making a computed field from its value storing it in the key - DocServer.GetRefField(node.attrs.fieldKey).then(options => { - (options instanceof Doc) && DocListCast(options.data).forEach(opt => StrCast(opt.title).startsWith(newText) && (newText = StrCast(opt.title))); - self._fieldSpan.innerHTML = self._dashDoc![self._fieldKey] = newText; - if (newText.startsWith(":=") && self._dashDoc && e.data === null && !e.inputType.includes("delete")) { - Doc.Layout(tbox.props.Document)[self._fieldKey] = ComputedField.MakeFunction(self._fieldSpan.innerText.substring(2)); - } - }); + self._fieldSpan.onblur?.(undefined as any); } }; @@ -937,6 +944,21 @@ export class DashFieldView { this._labelSpan.style.display = "inline"; this._labelSpan.style.fontWeight = "bold"; this._labelSpan.style.fontSize = "larger"; + this._labelSpan.onpointerdown = function (e: any) { + e.stopPropagation(); + if (tbox.props.ContainingCollectionDoc) { + const alias = Doc.MakeAlias(tbox.props.ContainingCollectionDoc); + alias.viewType = CollectionViewType.Time; + let list = Cast(alias.schemaColumns, listSpec(SchemaHeaderField)); + if (!list) { + alias.schemaColumns = list = new List(); + } + list.map(c => c.heading).indexOf("#") === -1 && list.push(new SchemaHeaderField("#", "#f1efeb")); + list.map(c => c.heading).indexOf("text") === -1 && list.push(new SchemaHeaderField("text", "#f1efeb")); + alias._pivotField = "#"; + tbox.props.addDocTab(alias, "onRight"); + } + } this._labelSpan.innerHTML = `${node.attrs.fieldKey}: `; if (node.attrs.docid) { DocServer.GetRefField(node.attrs.docid).then(async dashDoc => dashDoc instanceof Doc && runInAction(() => setDashDoc(dashDoc))); diff --git a/src/client/views/collections/CollectionMasonryViewFieldRow.tsx b/src/client/views/collections/CollectionMasonryViewFieldRow.tsx index 3c2cbb5b0..6ebd3194d 100644 --- a/src/client/views/collections/CollectionMasonryViewFieldRow.tsx +++ b/src/client/views/collections/CollectionMasonryViewFieldRow.tsx @@ -80,7 +80,7 @@ export class CollectionMasonryViewFieldRow extends React.Component d[key] = castedValue); this.props.parent.onInternalDrop(e, de); @@ -99,7 +99,7 @@ export class CollectionMasonryViewFieldRow extends React.Component { this._createAliasSelected = false; - const key = StrCast(this.props.parent.props.Document.sectionFilter); + const key = StrCast(this.props.parent.props.Document._pivotField); const castedValue = this.getValue(value); if (castedValue) { if (this.props.parent.sectionHeaders) { @@ -138,7 +138,7 @@ export class CollectionMasonryViewFieldRow extends React.Component { this._createAliasSelected = false; - const key = StrCast(this.props.parent.props.Document.sectionFilter); + const key = StrCast(this.props.parent.props.Document._pivotField); const newDoc = Docs.Create.TextDocument("", { _height: 18, _width: 200, title: value }); newDoc[key] = this.getValue(this.props.heading); return this.props.parent.props.addDocument(newDoc); @@ -146,7 +146,7 @@ export class CollectionMasonryViewFieldRow extends React.Component { this._createAliasSelected = false; - const key = StrCast(this.props.parent.props.Document.sectionFilter); + const key = StrCast(this.props.parent.props.Document._pivotField); this.props.docList.forEach(d => d[key] = undefined); if (this.props.parent.sectionHeaders && this.props.headingObject) { const index = this.props.parent.sectionHeaders.indexOf(this.props.headingObject); @@ -168,7 +168,7 @@ export class CollectionMasonryViewFieldRow extends React.Component this._sensitivity) { const alias = Doc.MakeAlias(this.props.parent.props.Document); - const key = StrCast(this.props.parent.props.Document.sectionFilter); + const key = StrCast(this.props.parent.props.Document._pivotField); let value = this.getValue(this._heading); value = typeof value === "string" ? `"${value}"` : value; const script = `return doc.${key} === ${value}`; @@ -296,7 +296,7 @@ export class CollectionMasonryViewFieldRow extends React.Component evContents, diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index d1f45af90..f84b0af20 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -31,21 +31,21 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { _masonryGridRef: HTMLDivElement | null = null; _draggerRef = React.createRef(); _heightDisposer?: IReactionDisposer; - _sectionFilterDisposer?: IReactionDisposer; + _pivotFieldDisposer?: IReactionDisposer; _docXfs: any[] = []; _columnStart: number = 0; @observable _heightMap = new Map(); @observable _cursor: CursorProperty = "grab"; @observable _scroll = 0; // used to force the document decoration to update when scrolling @computed get sectionHeaders() { return Cast(this.props.Document.sectionHeaders, listSpec(SchemaHeaderField)); } - @computed get sectionFilter() { return StrCast(this.props.Document.sectionFilter); } + @computed get pivotField() { return StrCast(this.props.Document._pivotField); } @computed get filteredChildren() { return this.childLayoutPairs.filter(pair => pair.layout instanceof Doc).map(pair => pair.layout); } @computed get xMargin() { return NumCast(this.props.Document._xMargin, 2 * Math.min(this.gridGap, .05 * this.props.PanelWidth())); } @computed get yMargin() { return Math.max(this.props.Document._showTitle && !this.props.Document._showTitleHover ? 30 : 0, NumCast(this.props.Document._yMargin, 0)); } // 2 * this.gridGap)); } @computed get gridGap() { return NumCast(this.props.Document._gridGap, 10); } @computed get isStackingView() { return BoolCast(this.props.Document.singleColumn, true); } @computed get numGroupColumns() { return this.isStackingView ? Math.max(1, this.Sections.size + (this.showAddAGroup ? 1 : 0)) : 1; } - @computed get showAddAGroup() { return (this.sectionFilter && (this.props.Document._chromeStatus !== 'view-mode' && this.props.Document._chromeStatus !== 'disabled')); } + @computed get showAddAGroup() { return (this.pivotField && (this.props.Document._chromeStatus !== 'view-mode' && this.props.Document._chromeStatus !== 'disabled')); } @computed get columnWidth() { return Math.min(this.props.PanelWidth() / (this.props as any).ContentScaling() - 2 * this.xMargin, this.isStackingView ? Number.MAX_VALUE : NumCast(this.props.Document.columnWidth, 250)); @@ -73,7 +73,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { } get Sections() { - if (!this.sectionFilter || this.sectionHeaders instanceof Promise) return new Map(); + if (!this.pivotField || this.sectionHeaders instanceof Promise) return new Map(); if (this.sectionHeaders === undefined) { setTimeout(() => this.props.Document.sectionHeaders = new List(), 0); @@ -83,18 +83,18 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { const fields = new Map(sectionHeaders.map(sh => [sh, []] as [SchemaHeaderField, []])); let changed = false; this.filteredChildren.map(d => { - const sectionValue = (d[this.sectionFilter] ? d[this.sectionFilter] : `NO ${this.sectionFilter.toUpperCase()} VALUE`) as object; + const sectionValue = (d[this.pivotField] ? d[this.pivotField] : `NO ${this.pivotField.toUpperCase()} VALUE`) as object; // the next five lines ensures that floating point rounding errors don't create more than one section -syip const parsed = parseInt(sectionValue.toString()); const castedSectionValue = !isNaN(parsed) ? parsed : sectionValue; // look for if header exists already - const existingHeader = sectionHeaders.find(sh => sh.heading === (castedSectionValue ? castedSectionValue.toString() : `NO ${this.sectionFilter.toUpperCase()} VALUE`)); + const existingHeader = sectionHeaders.find(sh => sh.heading === (castedSectionValue ? castedSectionValue.toString() : `NO ${this.pivotField.toUpperCase()} VALUE`)); if (existingHeader) { fields.get(existingHeader)!.push(d); } else { - const newSchemaHeader = new SchemaHeaderField(castedSectionValue ? castedSectionValue.toString() : `NO ${this.sectionFilter.toUpperCase()} VALUE`); + const newSchemaHeader = new SchemaHeaderField(castedSectionValue ? castedSectionValue.toString() : `NO ${this.pivotField.toUpperCase()} VALUE`); fields.set(newSchemaHeader, [d]); sectionHeaders.push(newSchemaHeader); changed = true; @@ -134,15 +134,15 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { ); // reset section headers when a new filter is inputted - this._sectionFilterDisposer = reaction( - () => this.sectionFilter, + this._pivotFieldDisposer = reaction( + () => this.pivotField, () => this.props.Document.sectionHeaders = new List() ); } componentWillUnmount() { super.componentWillUnmount(); - this._heightDisposer && this._heightDisposer(); - this._sectionFilterDisposer && this._sectionFilterDisposer(); + this._heightDisposer?.(); + this._pivotFieldDisposer?.(); } @action @@ -278,7 +278,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { } headings = () => Array.from(this.Sections.keys()); sectionStacking = (heading: SchemaHeaderField | undefined, docList: Doc[]) => { - const key = this.sectionFilter; + const key = this.pivotField; let type: "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" | undefined = undefined; const types = docList.length ? docList.map(d => typeof d[key]) : this.filteredChildren.map(d => typeof d[key]); if (types.map((i, idx) => types.indexOf(i) === idx).length === 1) { @@ -313,7 +313,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { } sectionMasonry = (heading: SchemaHeaderField | undefined, docList: Doc[]) => { - const key = this.sectionFilter; + const key = this.pivotField; let type: "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" | undefined = undefined; const types = docList.length ? docList.map(d => typeof d[key]) : this.filteredChildren.map(d => typeof d[key]); if (types.map((i, idx) => types.indexOf(i) === idx).length === 1) { @@ -341,7 +341,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { if (value && this.sectionHeaders) { const schemaHdrField = new SchemaHeaderField(value); this.sectionHeaders.push(schemaHdrField); - Doc.addEnumerationToTextField(undefined, this.sectionFilter, [Docs.Create.TextDocument(value, { title: value, _backgroundColor: schemaHdrField.color })]); + Doc.addEnumerationToTextField(undefined, this.pivotField, [Docs.Create.TextDocument(value, { title: value, _backgroundColor: schemaHdrField.color })]); return true; } return false; @@ -370,7 +370,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { @computed get renderedSections() { TraceMobx(); let sections = [[undefined, this.filteredChildren] as [SchemaHeaderField | undefined, Doc[]]]; - if (this.sectionFilter) { + if (this.pivotField) { const entries = Array.from(this.Sections.entries()); sections = entries.sort(this.sortFunc); } diff --git a/src/client/views/collections/CollectionStackingViewFieldColumn.tsx b/src/client/views/collections/CollectionStackingViewFieldColumn.tsx index 516e583d4..646b433bf 100644 --- a/src/client/views/collections/CollectionStackingViewFieldColumn.tsx +++ b/src/client/views/collections/CollectionStackingViewFieldColumn.tsx @@ -23,7 +23,6 @@ import { CollectionStackingView } from "./CollectionStackingView"; import { setupMoveUpEvents, emptyFunction } from "../../../Utils"; import "./CollectionStackingView.scss"; import { listSpec } from "../../../new_fields/Schema"; -import { Schema } from "prosemirror-model"; const higflyout = require("@hig/flyout"); export const { anchorPoints } = higflyout; export const Flyout = higflyout.default; @@ -62,7 +61,7 @@ export class CollectionStackingViewFieldColumn extends React.Component { if (de.complete.docDragData) { - const key = StrCast(this.props.parent.props.Document.sectionFilter); + const key = StrCast(this.props.parent.props.Document._pivotField); const castedValue = this.getValue(this._heading); de.complete.docDragData.droppedDocuments.forEach(d => Doc.SetInPlace(d, key, castedValue, false)); this.props.parent.onInternalDrop(e, de); @@ -85,7 +84,7 @@ export class CollectionStackingViewFieldColumn extends React.Component { - const key = StrCast(this.props.parent.props.Document.sectionFilter); + const key = StrCast(this.props.parent.props.Document._pivotField); const castedValue = this.getValue(value); if (castedValue) { if (this.props.parent.sectionHeaders) { @@ -126,7 +125,7 @@ export class CollectionStackingViewFieldColumn extends React.Component { if (!value) return false; - const key = StrCast(this.props.parent.props.Document.sectionFilter); + const key = StrCast(this.props.parent.props.Document._pivotField); const newDoc = Docs.Create.TextDocument(value, { _height: 18, _width: 200, title: value, _autoHeight: true }); newDoc[key] = this.getValue(this.props.heading); const maxHeading = this.props.docList.reduce((maxHeading, doc) => NumCast(doc.heading) > maxHeading ? NumCast(doc.heading) : maxHeading, 0); @@ -137,7 +136,7 @@ export class CollectionStackingViewFieldColumn extends React.Component { - const key = StrCast(this.props.parent.props.Document.sectionFilter); + const key = StrCast(this.props.parent.props.Document._pivotField); this.props.docList.forEach(d => d[key] = undefined); if (this.props.parent.sectionHeaders && this.props.headingObject) { const index = this.props.parent.sectionHeaders.indexOf(this.props.headingObject); @@ -161,8 +160,8 @@ export class CollectionStackingViewFieldColumn extends React.Component { const alias = Doc.MakeAlias(this.props.parent.props.Document); alias._width = this.props.parent.props.PanelWidth() / (Cast(this.props.parent.props.Document.sectionHeaders, listSpec(SchemaHeaderField))?.length || 1); - alias.sectionFilter = undefined; - const key = StrCast(this.props.parent.props.Document.sectionFilter); + alias._pivotField = undefined; + const key = StrCast(this.props.parent.props.Document._pivotField); let value = this.getValue(this._heading); value = typeof value === "string" ? `"${value}"` : value; alias.viewSpecScript = ScriptField.MakeFunction(`doc.${key} === ${value}`, { doc: Doc.name }); @@ -277,7 +276,7 @@ export class CollectionStackingViewFieldColumn extends React.Component c.title === this._currentKey).map(c => c.immediate(de.complete.docDragData ?.draggedDocuments || [])); + this._buttonizableCommands.filter(c => c.title === this._currentKey).map(c => c.immediate(de.complete.docDragData?.draggedDocuments || [])); e.stopPropagation(); } return true; @@ -472,7 +472,7 @@ export class CollectionStackingViewChrome extends React.Component => { value = value.toLowerCase(); @@ -510,26 +510,26 @@ export class CollectionStackingViewChrome extends React.Component { - this.props.CollectionView.props.Document.sectionFilter = value; + this.props.CollectionView.props.Document._pivotField = value; return true; } @action toggleSort = () => { this.props.CollectionView.props.Document.stackingHeadersSortDescending = !this.props.CollectionView.props.Document.stackingHeadersSortDescending; }; - @action resetValue = () => { this._currentKey = this.sectionFilter; }; + @action resetValue = () => { this._currentKey = this.pivotField; }; render() { return (
    -
    -
    +
    +
    GROUP ITEMS BY:
    -
    +
    this.sectionFilter} + GetValue={() => this.pivotField} autosuggestProps={ { resetValue: this.resetValue, @@ -551,7 +551,7 @@ export class CollectionStackingViewChrome extends React.Component
    diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 055be7f86..ea86bff99 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -1,20 +1,22 @@ import { library } from "@fortawesome/fontawesome-svg-core"; import { faEye } from "@fortawesome/free-regular-svg-icons"; -import { faBraille, faChalkboard, faCompass, faCompressArrowsAlt, faExpandArrowsAlt, faFileUpload, faPaintBrush, faTable, faUpload, faTextHeight } from "@fortawesome/free-solid-svg-icons"; -import { action, computed, observable, ObservableMap, reaction, runInAction, IReactionDisposer } from "mobx"; +import { faBraille, faChalkboard, faCompass, faCompressArrowsAlt, faExpandArrowsAlt, faFileUpload, faPaintBrush, faTable, faUpload } from "@fortawesome/free-solid-svg-icons"; +import { action, computed, IReactionDisposer, observable, ObservableMap, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; import { computedFn } from "mobx-utils"; -import { Doc, DocListCast, HeightSym, Opt, WidthSym, DocCastAsync } from "../../../../new_fields/Doc"; +import { Doc, HeightSym, Opt, WidthSym } from "../../../../new_fields/Doc"; import { documentSchema, positionSchema } from "../../../../new_fields/documentSchemas"; import { Id } from "../../../../new_fields/FieldSymbols"; -import { InkTool, InkField, InkData } from "../../../../new_fields/InkField"; +import { InkData, InkField, InkTool } from "../../../../new_fields/InkField"; +import { List } from "../../../../new_fields/List"; +import { RichTextField } from "../../../../new_fields/RichTextField"; import { createSchema, listSpec, makeInterface } from "../../../../new_fields/Schema"; import { ScriptField } from "../../../../new_fields/ScriptField"; -import { Cast, NumCast, ScriptCast, BoolCast, StrCast, FieldValue } from "../../../../new_fields/Types"; +import { BoolCast, Cast, FieldValue, NumCast, ScriptCast, StrCast } from "../../../../new_fields/Types"; import { TraceMobx } from "../../../../new_fields/util"; import { GestureUtils } from "../../../../pen-gestures/GestureUtils"; -import { CurrentUserUtils } from "../../../../server/authentication/models/current_user_utils"; import { aggregateBounds, intersectRect, returnOne, Utils } from "../../../../Utils"; +import { CognitiveServices } from "../../../cognitive_services/CognitiveServices"; import { DocServer } from "../../../DocServer"; import { Docs } from "../../../documents/Documents"; import { DocumentManager } from "../../../util/DocumentManager"; @@ -29,10 +31,11 @@ import { ContextMenu } from "../../ContextMenu"; import { ContextMenuProps } from "../../ContextMenuItem"; import { InkingControl } from "../../InkingControl"; import { CollectionFreeFormDocumentView } from "../../nodes/CollectionFreeFormDocumentView"; -import { DocumentContentsView } from "../../nodes/DocumentContentsView"; +import { DocumentViewProps } from "../../nodes/DocumentView"; import { FormattedTextBox } from "../../nodes/FormattedTextBox"; import { pageSchema } from "../../nodes/ImageBox"; import PDFMenu from "../../pdf/PDFMenu"; +import { CollectionDockingView } from "../CollectionDockingView"; import { CollectionSubView } from "../CollectionSubView"; import { computePivotLayout, computeTimelineLayout, PoolData, ViewDefBounds, ViewDefResult } from "./CollectionFreeFormLayoutEngines"; import { CollectionFreeFormRemoteCursors } from "./CollectionFreeFormRemoteCursors"; @@ -40,13 +43,6 @@ import "./CollectionFreeFormView.scss"; import MarqueeOptionsMenu from "./MarqueeOptionsMenu"; import { MarqueeView } from "./MarqueeView"; import React = require("react"); -import { CognitiveServices } from "../../../cognitive_services/CognitiveServices"; -import { RichTextField } from "../../../../new_fields/RichTextField"; -import { List } from "../../../../new_fields/List"; -import { DocumentViewProps } from "../../nodes/DocumentView"; -import { CollectionDockingView } from "../CollectionDockingView"; -import { MainView } from "../../MainView"; -import { TouchScrollableMenuItem } from "../../TouchScrollableMenu"; library.add(faEye as any, faTable, faPaintBrush, faExpandArrowsAlt, faCompressArrowsAlt, faCompass, faUpload, faBraille, faChalkboard, faFileUpload); diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 6216ab7e6..0f8d8fec8 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -254,7 +254,7 @@ export class CurrentUserUtils { // Finally, setup the list of buttons to display in the sidebar doc.sidebarButtons = Docs.Create.StackingDocument([doc.SearchBtn as Doc, doc.LibraryBtn as Doc, doc.ToolsBtn as Doc], { - _width: 500, _height: 80, boxShadow: "0 0", sectionFilter: "title", hideHeadings: true, ignoreClick: true, + _width: 500, _height: 80, boxShadow: "0 0", _pivotField: "title", hideHeadings: true, ignoreClick: true, _chromeStatus: "disabled", title: "library stack", backgroundColor: "dimGray", }); } -- cgit v1.2.3-70-g09d2 From a88608f33c15a79fecda08e3fddb5bc7690af127 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Tue, 3 Mar 2020 21:19:20 -0500 Subject: fixed enumerations a bit. --- src/client/documents/Documents.ts | 1 + src/client/util/RichTextSchema.tsx | 57 ++++++++++------------ .../views/collections/CollectionStackingView.tsx | 2 +- src/new_fields/Doc.ts | 35 ++++--------- .../authentication/models/current_user_utils.ts | 16 +++--- 5 files changed, 44 insertions(+), 67 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 6b25b3897..b06ff5465 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -108,6 +108,7 @@ export interface DocumentOptions { _backgroundColor?: string | ScriptField; // background color for each template layout doc ( overrides backgroundColor ) color?: string; // foreground color data doc _color?: string; // foreground color for each template layout doc (overrides color) + caption?: RichTextField; ignoreClick?: boolean; lockedPosition?: boolean; // lock the x,y coordinates of the document so that it can't be dragged lockedTransform?: boolean; // lock the panx,pany and scale parameters of the document so that it be panned/zoomed diff --git a/src/client/util/RichTextSchema.tsx b/src/client/util/RichTextSchema.tsx index 2c3714310..649908317 100644 --- a/src/client/util/RichTextSchema.tsx +++ b/src/client/util/RichTextSchema.tsx @@ -887,32 +887,10 @@ export class DashFieldView { this._enumerables.onpointerdown = async (e) => { e.stopPropagation(); - const collview = await Doc.addEnumerationToTextField(self._textBoxDoc, node.attrs.fieldKey, [Docs.Create.TextDocument(self._fieldSpan.innerText, { title: self._fieldSpan.innerText })]); + const collview = await Doc.addFieldEnumerations(self._textBoxDoc, node.attrs.fieldKey, [{ title: self._fieldSpan.innerText }]); collview instanceof Doc && tbox.props.addDocTab(collview, "onRight"); } - - this._fieldSpan = document.createElement("div"); - this._fieldSpan.id = Utils.GenerateGuid(); - this._fieldSpan.contentEditable = "true"; - this._fieldSpan.style.position = "relative"; - this._fieldSpan.style.display = "inline-block"; - this._fieldSpan.style.minWidth = "5px"; - this._fieldSpan.style.backgroundColor = "rgba(155, 155, 155, 0.24)"; - this._fieldSpan.onkeypress = function (e: any) { e.stopPropagation(); }; - this._fieldSpan.onkeyup = function (e: any) { e.stopPropagation(); }; - this._fieldSpan.onmousedown = function (e: any) { - e.stopPropagation(); - self._enumerables.style.display = "inline-block"; - }; - this._fieldSpan.oncontextmenu = function (e: any) { - ContextMenu.Instance.addItem({ - description: "Show Enumeration Templates", event: () => { - e.stopPropagation(); - DocServer.GetRefField(node.attrs.fieldKey).then(collview => collview instanceof Doc && tbox.props.addDocTab(collview, "onRight")); - }, icon: "expand-arrows-alt" - }); - }; - this._fieldSpan.onblur = function (e: any) { + const updateText = (forceMatch: boolean) => { self._enumerables.style.display = "none"; let newText = self._fieldSpan.innerText.startsWith(":=") ? ":=-computed-" : self._fieldSpan.innerText; @@ -920,8 +898,12 @@ export class DashFieldView { // holds the different enumerated values for the field in the titles of its collected documents. // if there's a partial match from the start of the input text, complete the text --- TODO: make this an auto suggest box and select from a drop down. DocServer.GetRefField(node.attrs.fieldKey).then(options => { - (options instanceof Doc) && DocListCast(options.data).forEach(opt => StrCast(opt.title).startsWith(newText) && (newText = StrCast(opt.title))); - self._fieldSpan.innerHTML = self._dashDoc![self._fieldKey] = newText; + let modText = ""; + (options instanceof Doc) && DocListCast(options.data).forEach(opt => (forceMatch ? StrCast(opt.title).startsWith(newText) : StrCast(opt.title) === newText) && (modText = StrCast(opt.title))); + if (modText) { + self._fieldSpan.innerHTML = self._dashDoc![self._fieldKey] = modText; + Doc.addFieldEnumerations(self._textBoxDoc, node.attrs.fieldKey, []); + } // if the text starts with a ':=' then treat it as an expression by making a computed field from its value storing it in the key if (newText.startsWith(":=") && self._dashDoc && e.data === null && !e.inputType.includes("delete")) { @@ -930,10 +912,22 @@ export class DashFieldView { }); } + this._fieldSpan = document.createElement("div"); + this._fieldSpan.id = Utils.GenerateGuid(); + this._fieldSpan.contentEditable = "true"; + this._fieldSpan.style.position = "relative"; + this._fieldSpan.style.display = "inline-block"; + this._fieldSpan.style.minWidth = "5px"; + this._fieldSpan.style.backgroundColor = "rgba(155, 155, 155, 0.24)"; + this._fieldSpan.onkeypress = function (e: any) { e.stopPropagation(); }; + this._fieldSpan.onkeyup = function (e: any) { e.stopPropagation(); }; + this._fieldSpan.onmousedown = function (e: any) { e.stopPropagation(); self._enumerables.style.display = "inline-block"; }; + this._fieldSpan.onblur = function (e: any) { updateText(false); } + const setDashDoc = (doc: Doc) => { self._dashDoc = doc; - if (this._dashDoc && self._options?.length && !this._dashDoc[node.attrs.fieldKey]) { - this._dashDoc[node.attrs.fieldKey] = StrCast(self._options[0].title); + if (self._dashDoc && self._options?.length && !self._dashDoc[node.attrs.fieldKey]) { + self._dashDoc[node.attrs.fieldKey] = StrCast(self._options[0].title); } } this._fieldSpan.onkeydown = function (e: any) { @@ -949,10 +943,8 @@ export class DashFieldView { } if (e.key === "Enter") { e.preventDefault(); - if (e.ctrlKey) { - Doc.addEnumerationToTextField(self._textBoxDoc, node.attrs.fieldKey, [Docs.Create.TextDocument(self._fieldSpan.innerText, { title: self._fieldSpan.innerText })]); - } - self._fieldSpan.onblur?.(undefined as any); + e.ctrlKey && Doc.addFieldEnumerations(self._textBoxDoc, node.attrs.fieldKey, [{ title: self._fieldSpan.innerText }]); + updateText(true); } }; @@ -997,6 +989,7 @@ export class DashFieldView { this._fieldWrapper.appendChild(this._fieldSpan); this._fieldWrapper.appendChild(this._enumerables); (this as any).dom = this._fieldWrapper; + updateText(false); } destroy() { this._reactionDisposer?.(); diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index f84b0af20..3f7f0a352 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -341,7 +341,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { if (value && this.sectionHeaders) { const schemaHdrField = new SchemaHeaderField(value); this.sectionHeaders.push(schemaHdrField); - Doc.addEnumerationToTextField(undefined, this.pivotField, [Docs.Create.TextDocument(value, { title: value, _backgroundColor: schemaHdrField.color })]); + Doc.addFieldEnumerations(undefined, this.pivotField, [{ title: value, _backgroundColor: schemaHdrField.color }]); return true; } return false; diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index 6d94f050c..ce69d95b7 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -847,40 +847,23 @@ export namespace Doc { return id; } - // setup a document to use enumerated values for a specified field name: - // doc: text document - // layoutString: species which text field receives the document's main text (e.g., FormattedTextBox.LayoutString("Todo") ) - // enumeratedFieldKey : specifies which enumerated field of the document is displayed in the caption (e.g., taskStatus) - // captionKey: specifies which field holds the caption template (e.g., caption) -- ideally this wouldn't be needed but would be derived from the layoutString's target field key - // - export function enumeratedTextTemplate(doc: Doc, layoutString: string, enumeratedFieldKey: string, enumeratedDocs: Doc[], captionKey: string = "caption") { - doc.caption = RichTextField.DashField(enumeratedFieldKey); - doc._showCaption = captionKey; - doc.layout = layoutString; - - Doc.addEnumerationToTextField(doc, enumeratedFieldKey, enumeratedDocs); - } - - export async function getEnumerationTextField(enumeratedFieldKey: string) { - return (await DocServer.GetRefField(enumeratedFieldKey)) as Doc; - } - - export async function addEnumerationToTextField(doc: Opt, enumeratedFieldKey: string, enumeratedDocs: Doc[]) { + export async function addFieldEnumerations(doc: Opt, enumeratedFieldKey: string, enumerations: { title: string, _backgroundColor?: string, color?: string }[]) { let optionsCollection = await DocServer.GetRefField(enumeratedFieldKey); if (!(optionsCollection instanceof Doc)) { optionsCollection = Docs.Create.StackingDocument([], { title: `${enumeratedFieldKey} field set` }, enumeratedFieldKey); Doc.AddDocToList((Doc.UserDoc().fieldTypes as Doc), "data", optionsCollection as Doc); } const options = optionsCollection as Doc; - doc && (Doc.GetProto(doc).backgroundColor = ComputedField.MakeFunction(`options.data.find(doc => doc.title === (this.expandedTemplate||this).${enumeratedFieldKey})?._backgroundColor || "white"`, undefined, { options })); - doc && (Doc.GetProto(doc).color = ComputedField.MakeFunction(`options.data.find(doc => doc.title === (this.expandedTemplate||this).${enumeratedFieldKey}).color || "black"`, undefined, { options })); - enumeratedDocs.map(enumeratedDoc => { - const found = DocListCast(options.data).find(d => d.title === enumeratedDoc.title); + const targetDoc = doc && Doc.GetProto(Cast(doc.expandedTemplate, Doc, null) || doc); + targetDoc && (targetDoc.backgroundColor = ComputedField.MakeFunction(`options.data.find(doc => doc.title === (this.expandedTemplate||this)["${enumeratedFieldKey}"])?._backgroundColor || "white"`, undefined, { options })); + targetDoc && (targetDoc.color = ComputedField.MakeFunction(`options.data.find(doc => doc.title === (this.expandedTemplate||this)["${enumeratedFieldKey}"]).color || "black"`, undefined, { options })); + enumerations.map(enumeration => { + const found = DocListCast(options.data).find(d => d.title === enumeration.title); if (found) { - found._backgroundColor = enumeratedDoc._backgroundColor || found._backgroundColor; - found._color = enumeratedDoc._color || found._color; + found._backgroundColor = enumeration._backgroundColor || found._backgroundColor; + found._color = enumeration.color || found._color; } else { - Doc.AddDocToList(options, "data", enumeratedDoc); + Doc.AddDocToList(options, "data", Docs.Create.TextDocument(enumeration.title, enumeration)); } }); return optionsCollection; diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 0f8d8fec8..f672da085 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -37,20 +37,20 @@ export class CurrentUserUtils { @observable public static GuestMobile: Doc | undefined; static setupDefaultDocTemplates(doc: Doc, buttons?: string[]) { - const taskStatusValues = [ - Docs.Create.TextDocument("todo", { title: "todo", _backgroundColor: "blue", color: "white" }), - Docs.Create.TextDocument("in progress", { title: "in progress", _backgroundColor: "yellow", color: "black" }), - Docs.Create.TextDocument("completed", { title: "completed", _backgroundColor: "green", color: "white" }) + const taskStatusValues = [ { title: "todo", _backgroundColor: "blue", color: "white" }, + { title: "in progress", _backgroundColor: "yellow", color: "black" }, + { title: "completed", _backgroundColor: "green", color: "white" } ]; const noteTemplates = [ Docs.Create.TextDocument("", { title: "text", style: "Note", isTemplateDoc: true, backgroundColor: "yellow" }), Docs.Create.TextDocument("", { title: "text", style: "Idea", isTemplateDoc: true, backgroundColor: "pink" }), Docs.Create.TextDocument("", { title: "text", style: "Topic", isTemplateDoc: true, backgroundColor: "lightBlue" }), Docs.Create.TextDocument("", { title: "text", style: "Person", isTemplateDoc: true, backgroundColor: "lightGreen" }), - Docs.Create.TextDocument("", { title: "text", style: "Todo", isTemplateDoc: true, backgroundColor: "orange", _autoHeight: false, _height: 100, _showCaption: "caption" }) + Docs.Create.TextDocument("", { title: "text", style: "Todo", isTemplateDoc: true, backgroundColor: "orange",_autoHeight: false, + layout:FormattedTextBox.LayoutString("Todo"), _height: 100, _showCaption: "caption",caption: RichTextField.DashField("taskStatus") }) ]; doc.fieldTypes = Docs.Create.TreeDocument([], { title: "field enumerations" }); - Doc.enumeratedTextTemplate(Doc.GetProto(noteTemplates[4]), FormattedTextBox.LayoutString("Todo"), "taskStatus", taskStatusValues); + Doc.addFieldEnumerations(Doc.GetProto(noteTemplates[4]), "taskStatus", taskStatusValues); doc.noteTypes = new PrefetchProxy(Docs.Create.TreeDocument(noteTemplates.map(nt => makeTemplate(nt, true, StrCast(nt.style)) ? nt : nt), { title: "Note Types", _height: 75 })); } @@ -268,9 +268,9 @@ export class CurrentUserUtils { ], { _width: 400, _height: 300, title: "slideView", _chromeStatus: "disabled", _xMargin: 3, _yMargin: 3, _autoHeight: false }); slideTemplate.isTemplateDoc = makeTemplate(slideTemplate); - const descriptionTemplate = Docs.Create.TextDocument("", { title: "descriptionView", _height: 100, _showTitle: "title" }); + const descriptionTemplate = Docs.Create.TextDocument("", { title: "text", _height: 100, _showTitle: "title" }); Doc.GetProto(descriptionTemplate).layout = FormattedTextBox.LayoutString("description"); - descriptionTemplate.isTemplateDoc = makeTemplate(descriptionTemplate); + descriptionTemplate.isTemplateDoc = makeTemplate(descriptionTemplate, true, "descriptionView"); const iconDoc = Docs.Create.TextDocument("", { title: "icon", _width: 150, _height: 30, isTemplateDoc: true, onClick: ScriptField.MakeScript("setNativeView(this)") }); Doc.GetProto(iconDoc).data = new RichTextField('{"doc":{"type":"doc","content":[{"type":"paragraph","attrs":{"align":null,"color":null,"id":null,"indent":null,"inset":null,"lineSpacing":null,"paddingBottom":null,"paddingTop":null},"content":[{"type":"dashField","attrs":{"fieldKey":"title","docid":""}}]}]},"selection":{"type":"text","anchor":2,"head":2},"storedMarks":[]}', ""); -- cgit v1.2.3-70-g09d2 From 4863b1ef9ec3160b0888a5ab8bb1a62274aed5ec Mon Sep 17 00:00:00 2001 From: bob Date: Fri, 6 Mar 2020 17:29:27 -0500 Subject: made tree views display documentViews instead of just strings --- src/client/documents/Documents.ts | 1 + src/client/util/DocumentManager.ts | 11 ++++- src/client/views/DocumentDecorations.tsx | 3 +- .../views/collections/CollectionSchemaCells.tsx | 3 +- .../views/collections/CollectionTreeView.scss | 3 ++ .../views/collections/CollectionTreeView.tsx | 52 +++++++++++++++++++--- src/client/views/nodes/DocuLinkBox.scss | 7 ++- src/client/views/nodes/DocuLinkBox.tsx | 11 +++-- src/client/views/nodes/DocumentView.scss | 2 + src/client/views/nodes/DocumentView.tsx | 14 ++++-- .../authentication/models/current_user_utils.ts | 14 +++--- 11 files changed, 95 insertions(+), 26 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 5f0e63b56..1f351e93f 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -123,6 +123,7 @@ export interface DocumentOptions { displayTimecode?: number; // the time that a document should be displayed (e.g., time an annotation should be displayed on a video) borderRounding?: string; boxShadow?: string; + dontRegisterChildren?: boolean; _pivotField?: string; // field key used to determine headings for sections in stacking, masonry, pivot views schemaColumns?: List; dockingConfig?: string; diff --git a/src/client/util/DocumentManager.ts b/src/client/util/DocumentManager.ts index 323d31af2..6711947ad 100644 --- a/src/client/util/DocumentManager.ts +++ b/src/client/util/DocumentManager.ts @@ -92,10 +92,17 @@ export class DocumentManager { public getDocumentViews(toFind: Doc): DocumentView[] { const toReturn: DocumentView[] = []; + // heurstic to return the "best" documents first: + // choose an exact match over an alias match + // choose documents that have a PanelWidth() over those that don't (the treeview documents have no panelWidth) DocumentManager.Instance.DocumentViews.map(view => - view.props.Document.presBox === undefined && view.props.Document === toFind && toReturn.push(view)); + view.props.Document.presBox === undefined && view.props.PanelWidth() > 1 && view.props.Document === toFind && toReturn.push(view)); DocumentManager.Instance.DocumentViews.map(view => - view.props.Document.presBox === undefined && view.props.Document !== toFind && Doc.AreProtosEqual(view.props.Document, toFind) && toReturn.push(view)); + view.props.Document.presBox === undefined && view.props.PanelWidth() <= 1 && view.props.Document === toFind && toReturn.push(view)); + DocumentManager.Instance.DocumentViews.map(view => + view.props.Document.presBox === undefined && view.props.PanelWidth() > 1 && view.props.Document !== toFind && Doc.AreProtosEqual(view.props.Document, toFind) && toReturn.push(view)); + DocumentManager.Instance.DocumentViews.map(view => + view.props.Document.presBox === undefined && view.props.PanelWidth() <= 1 && view.props.Document !== toFind && Doc.AreProtosEqual(view.props.Document, toFind) && toReturn.push(view)); return toReturn; } diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index c98be0d4a..39d078a36 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -43,7 +43,7 @@ export type CloseCall = (toBeDeleted: DocumentView[]) => void; export class DocumentDecorations extends React.Component<{}, { value: string }> { static Instance: DocumentDecorations; private _resizeHdlId = ""; - private _keyinput: React.RefObject; + private _keyinput = React.createRef(); private _resizeBorderWidth = 16; private _linkBoxHeight = 20 + 3; // link button height + margin private _titleHeight = 20; @@ -62,7 +62,6 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> constructor(props: Readonly<{}>) { super(props); DocumentDecorations.Instance = this; - this._keyinput = React.createRef(); reaction(() => SelectionManager.SelectedDocuments().slice(), docs => this.titleBlur(false)); } diff --git a/src/client/views/collections/CollectionSchemaCells.tsx b/src/client/views/collections/CollectionSchemaCells.tsx index df7abad61..79b5d7bb7 100644 --- a/src/client/views/collections/CollectionSchemaCells.tsx +++ b/src/client/views/collections/CollectionSchemaCells.tsx @@ -77,7 +77,8 @@ export class CollectionSchemaCell extends React.Component { @action isEditingCallback = (isEditing: boolean): void => { - document.addEventListener("keydown", this.onKeyDown); + document.removeEventListener("keydown", this.onKeyDown); + isEditing && document.addEventListener("keydown", this.onKeyDown); this._isEditing = isEditing; this.props.setIsEditing(isEditing); this.props.changeFocusedCellByIndex(this.props.row, this.props.col); diff --git a/src/client/views/collections/CollectionTreeView.scss b/src/client/views/collections/CollectionTreeView.scss index 6ebe81545..fd4a963c3 100644 --- a/src/client/views/collections/CollectionTreeView.scss +++ b/src/client/views/collections/CollectionTreeView.scss @@ -123,6 +123,9 @@ .editableView-container-editing-oneLine { min-width: 15px; } + .documentView-node-topmost { + width: unset; + } } .treeViewItem-header-above { diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index deff3d177..54ad2ad48 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -10,7 +10,7 @@ import { Document, listSpec } from '../../../new_fields/Schema'; import { ComputedField, ScriptField } from '../../../new_fields/ScriptField'; import { BoolCast, Cast, NumCast, ScriptCast, StrCast } from '../../../new_fields/Types'; import { CurrentUserUtils } from '../../../server/authentication/models/current_user_utils'; -import { emptyFunction, emptyPath, returnFalse, Utils } from '../../../Utils'; +import { emptyFunction, emptyPath, returnFalse, Utils, returnOne, returnZero, returnTransparent, returnTrue } from '../../../Utils'; import { Docs, DocUtils } from '../../documents/Documents'; import { DocumentType } from "../../documents/DocumentTypes"; import { DocumentManager } from '../../util/DocumentManager'; @@ -34,6 +34,7 @@ import "./CollectionTreeView.scss"; import React = require("react"); import { CollectionViewType } from './CollectionView'; import { RichTextField } from '../../../new_fields/RichTextField'; +import { DocumentView } from '../nodes/DocumentView'; export interface TreeViewProps { @@ -92,6 +93,7 @@ class TreeView extends React.Component { private _header?: React.RefObject = React.createRef(); private _treedropDisposer?: DragManager.DragDropDisposer; private _dref = React.createRef(); + private _tref = React.createRef(); get displayName() { return "TreeView(" + this.props.document.title + ")"; } // this makes mobx trace() statements more descriptive @@ -171,13 +173,16 @@ class TreeView extends React.Component { editableView = (key: string, style?: string) => ( StrCast(this.props.document[key])} - SetValue={undoBatch((value: string) => Doc.SetInPlace(this.props.document, key, value, false) || true)} + SetValue={undoBatch((value: string) => { + Doc.SetInPlace(this.props.document, key, value, false) || true; + this.props.document.editTitle = undefined; + })} OnFillDown={undoBatch((value: string) => { Doc.SetInPlace(this.props.document, key, value, false); const doc = Docs.Create.FreeformDocument([], { title: "", x: 0, y: 0, _width: 100, _height: 25, templates: new List([Templates.Title.Layout]) }); @@ -263,6 +268,13 @@ class TreeView extends React.Component { const finalXf = this.props.ScreenToLocalTransform().translate(offset[0], offset[1] + (this.props.ChromeHeight && this.props.ChromeHeight() < 0 ? this.props.ChromeHeight() : 0)); return finalXf; } + getTransform = () => { + const { scale, translateX, translateY } = Utils.GetScreenTransform(this._tref.current!); + const outerXf = this.props.outerXf(); + const offset = this.props.ScreenToLocalTransform().transformDirection(outerXf.translateX - translateX, outerXf.translateY - translateY); + const finalXf = this.props.ScreenToLocalTransform().translate(offset[0], offset[1]); + return finalXf; + } docWidth = () => { const layoutDoc = Doc.Layout(this.props.document); const aspect = NumCast(layoutDoc._nativeHeight) / NumCast(layoutDoc._nativeWidth); @@ -404,8 +416,8 @@ class TreeView extends React.Component { */ @computed get renderTitle() { - const reference = React.createRef(); - const onItemDown = SetupDrag(reference, () => this.dataDoc, this.move, this.props.dropAction, this.props.treeViewId[Id], true); + const onItemDown = SetupDrag(this._tref, () => this.dataDoc, this.move, this.props.dropAction, this.props.treeViewId[Id], true); + const editTitle = ScriptField.MakeFunction("this.editTitle=true", { this: Doc.name }); const headerElements = ( {
    ); return <> -
    - {this.editableView("title")} + {this.props.document.editTitle ? + this.editableView("title") : + }
    {this.props.treeViewHideHeaderFields() ? (null) : headerElements} {openRight} diff --git a/src/client/views/nodes/DocuLinkBox.scss b/src/client/views/nodes/DocuLinkBox.scss index 286033475..f2c203548 100644 --- a/src/client/views/nodes/DocuLinkBox.scss +++ b/src/client/views/nodes/DocuLinkBox.scss @@ -1,4 +1,4 @@ -.docuLinkBox-cont { +.docuLinkBox-cont, .docuLinkBox-cont-small { cursor: default; position: absolute; width: 15; @@ -21,4 +21,9 @@ padding-left: 2px; padding-top: 1px; } +} + +.docuLinkBox-cont-small { + width:5px; + height:5px; } \ No newline at end of file diff --git a/src/client/views/nodes/DocuLinkBox.tsx b/src/client/views/nodes/DocuLinkBox.tsx index 882e57006..776d2019d 100644 --- a/src/client/views/nodes/DocuLinkBox.tsx +++ b/src/client/views/nodes/DocuLinkBox.tsx @@ -124,8 +124,8 @@ export class DocuLinkBox extends DocComponent(Doc } render() { - const x = NumCast(this.props.Document[this.props.fieldKey + "_x"], 100); - const y = NumCast(this.props.Document[this.props.fieldKey + "_y"], 100); + const x = this.props.PanelWidth() > 1 ? NumCast(this.props.Document[this.props.fieldKey + "_x"], 100) : 0; + const y = this.props.PanelWidth() > 1 ? NumCast(this.props.Document[this.props.fieldKey + "_y"], 100) : 0; const c = StrCast(this.props.Document.backgroundColor, "lightblue"); const anchor = this.props.fieldKey === "anchor1" ? "anchor2" : "anchor1"; const anchorScale = (x === 0 || x === 100 || y === 0 || y === 100) ? 1 : .15; @@ -140,9 +140,12 @@ export class DocuLinkBox extends DocComponent(Doc
    }
    ); - return
    {!this._editing && !this._forceOpen ? (null) : diff --git a/src/client/views/nodes/DocumentView.scss b/src/client/views/nodes/DocumentView.scss index 56e3eb220..d1d96f0a1 100644 --- a/src/client/views/nodes/DocumentView.scss +++ b/src/client/views/nodes/DocumentView.scss @@ -5,6 +5,8 @@ position: inherit; top: 0; left: 0; + width: 100%; + height: 100%; border-radius: inherit; transition: outline .3s linear; cursor: grab; diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 7d2940df5..463c6b5bd 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -1018,6 +1018,16 @@ export class DocumentView extends DocComponent(Docu @computed get innards() { TraceMobx(); + if (!this.props.PanelWidth()) { + return
    + {StrCast(this.props.Document.title)} + {this.Document.links && DocListCast(this.Document.links).filter(d => !d.hidden).filter(this.isNonTemporalLink).map((d, i) => +
    + doc.hidden = true)} /> +
    )} +
    ; + } const showTitle = StrCast(this.layoutDoc._showTitle); const showTitleHover = StrCast(this.layoutDoc._showTitleHover); const showCaption = StrCast(this.layoutDoc._showCaption); @@ -1116,8 +1126,6 @@ export class DocumentView extends DocComponent(Docu border: highlighting && borderRounding ? `${highlightStyles[fullDegree]} ${highlightColors[fullDegree]} ${localScale}px` : undefined, boxShadow: this.props.Document.isTemplateForField ? "black 0.2vw 0.2vw 0.8vw" : undefined, background: finalColor, - width: "100%", - height: "100%", opacity: this.Document.opacity }}> {this.Document.isBackground ?
    : (null)} @@ -1131,7 +1139,7 @@ export class DocumentView extends DocComponent(Docu } } -Scripting.addGlobal(function toggleDetail(doc: any, layoutKey: string, otherKey: string="layout") { +Scripting.addGlobal(function toggleDetail(doc: any, layoutKey: string, otherKey: string = "layout") { const dv = DocumentManager.Instance.getDocumentView(doc); if (dv?.props.Document.layoutKey === layoutKey) dv?.switchViews(otherKey !== "layout", otherKey.replace("layout_", "")); else dv?.switchViews(true, layoutKey.replace("layout_", "")); diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index f672da085..5d93f208a 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -37,17 +37,19 @@ export class CurrentUserUtils { @observable public static GuestMobile: Doc | undefined; static setupDefaultDocTemplates(doc: Doc, buttons?: string[]) { - const taskStatusValues = [ { title: "todo", _backgroundColor: "blue", color: "white" }, - { title: "in progress", _backgroundColor: "yellow", color: "black" }, - { title: "completed", _backgroundColor: "green", color: "white" } + const taskStatusValues = [{ title: "todo", _backgroundColor: "blue", color: "white" }, + { title: "in progress", _backgroundColor: "yellow", color: "black" }, + { title: "completed", _backgroundColor: "green", color: "white" } ]; const noteTemplates = [ Docs.Create.TextDocument("", { title: "text", style: "Note", isTemplateDoc: true, backgroundColor: "yellow" }), Docs.Create.TextDocument("", { title: "text", style: "Idea", isTemplateDoc: true, backgroundColor: "pink" }), Docs.Create.TextDocument("", { title: "text", style: "Topic", isTemplateDoc: true, backgroundColor: "lightBlue" }), Docs.Create.TextDocument("", { title: "text", style: "Person", isTemplateDoc: true, backgroundColor: "lightGreen" }), - Docs.Create.TextDocument("", { title: "text", style: "Todo", isTemplateDoc: true, backgroundColor: "orange",_autoHeight: false, - layout:FormattedTextBox.LayoutString("Todo"), _height: 100, _showCaption: "caption",caption: RichTextField.DashField("taskStatus") }) + Docs.Create.TextDocument("", { + title: "text", style: "Todo", isTemplateDoc: true, backgroundColor: "orange", _autoHeight: false, + layout: FormattedTextBox.LayoutString("Todo"), _height: 100, _showCaption: "caption", caption: RichTextField.DashField("taskStatus") + }) ]; doc.fieldTypes = Docs.Create.TreeDocument([], { title: "field enumerations" }); Doc.addFieldEnumerations(Doc.GetProto(noteTemplates[4]), "taskStatus", taskStatusValues); @@ -221,7 +223,7 @@ export class CurrentUserUtils { _width: 50, _height: 25, title: "Library", fontSize: 10, letterSpacing: "0px", textTransform: "unset", borderRounding: "5px 5px 0px 0px", boxShadow: "3px 3px 0px rgb(34, 34, 34)", sourcePanel: Docs.Create.TreeDocument([doc.workspaces as Doc, doc.documents as Doc, Docs.Prototypes.MainLinkDocument(), doc, doc.recentlyClosed as Doc], { - title: "Library", _xMargin: 5, _yMargin: 5, _gridGap: 5, forceActive: true, dropAction: "alias", lockedPosition: true, boxShadow: "0 0", + title: "Library", _xMargin: 5, _yMargin: 5, _gridGap: 5, forceActive: true, dropAction: "alias", lockedPosition: true, boxShadow: "0 0", dontRegisterChildren: true }), targetContainer: sidebarContainer, onClick: ScriptField.MakeScript("this.targetContainer.proto = this.sourcePanel;") -- cgit v1.2.3-70-g09d2 From 4eaec2585a4f38a826707f2cf850d287276d9b14 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Tue, 10 Mar 2020 00:39:30 -0400 Subject: fixed up iconifying of different document types. fixed selection to not select toolbar tabs. fixed outline-like document creation in tree views. --- src/client/documents/Documents.ts | 1 + src/client/views/DocumentDecorations.tsx | 1 + .../views/collections/CollectionTreeView.tsx | 6 +++-- src/client/views/nodes/DocumentView.tsx | 28 ++++++++++++++++------ src/client/views/nodes/ImageBox.tsx | 2 +- src/new_fields/Doc.ts | 2 +- .../authentication/models/current_user_utils.ts | 16 +++++++++---- 7 files changed, 40 insertions(+), 16 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 901b3684f..131a48a2b 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -114,6 +114,7 @@ export interface DocumentOptions { lockedTransform?: boolean; // lock the panx,pany and scale parameters of the document so that it be panned/zoomed opacity?: number; defaultBackgroundColor?: string; + dontSelect?: boolean; // whether document decorations should be displayed when the document is selected isBackground?: boolean; isButton?: boolean; columnWidth?: number; diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 2ec170ddb..c4abc935f 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -69,6 +69,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> get Bounds(): { x: number, y: number, b: number, r: number } { return SelectionManager.SelectedDocuments().reduce((bounds, documentView) => { if (documentView.props.renderDepth === 0 || + documentView.props.Document.dontSelect || Doc.AreProtosEqual(documentView.props.Document, CurrentUserUtils.UserDocument)) { return bounds; } diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index 54ad2ad48..4757e5a53 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -185,8 +185,10 @@ class TreeView extends React.Component { })} OnFillDown={undoBatch((value: string) => { Doc.SetInPlace(this.props.document, key, value, false); - const doc = Docs.Create.FreeformDocument([], { title: "", x: 0, y: 0, _width: 100, _height: 25, templates: new List([Templates.Title.Layout]) }); - EditableView.loadId = doc[Id]; + const doc = Docs.Create.FreeformDocument([], { title: "-", x: 0, y: 0, _width: 100, _height: 25, templates: new List([Templates.Title.Layout]) }); + //EditableView.loadId = doc[Id]; + this.props.document.editTitle = undefined; + doc.editTitle = true; return this.props.addDocument(doc); })} onClick={() => { diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index dc529b79b..bf5f936d1 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -281,6 +281,7 @@ export class DocumentView extends DocComponent(Docu (Math.abs(e.clientX - this._downX) < Utils.DRAG_THRESHOLD && Math.abs(e.clientY - this._downY) < Utils.DRAG_THRESHOLD)) { e.stopPropagation(); let preventDefault = true; + this.props.bringToFront(this.props.Document); if (this._doubleTap && this.props.renderDepth && !this.onClickHandler?.script) { // disable double-click to show full screen for things that have an on click behavior since clicking them twice can be misinterpreted as a double click const fullScreenAlias = Doc.MakeAlias(this.props.Document); if (StrCast(fullScreenAlias.layoutKey) !== "layout_fullScreen" && fullScreenAlias.layout_fullScreen) { @@ -291,7 +292,10 @@ export class DocumentView extends DocComponent(Docu Doc.UnBrushDoc(this.props.Document); } else if (this.onClickHandler?.script) { SelectionManager.DeselectAll(); - UndoManager.RunInBatch(() => this.onClickHandler!.script.run({ this: this.Document.isTemplateForField && this.props.DataDoc ? this.props.DataDoc : this.props.Document, containingCollection: this.props.ContainingCollectionDoc, shiftKey: e.shiftKey }, console.log) && this.select(false), "on click"); + UndoManager.RunInBatch(() => this.onClickHandler!.script.run({ + this: this.Document.isTemplateForField && this.props.DataDoc ? this.props.DataDoc : this.props.Document, // try this.props.Document.expandedTemplate || this.props.Document + containingCollection: this.props.ContainingCollectionDoc, shiftKey: e.shiftKey + }, console.log) && !BoolCast(this.props.Document.dontSelect) && this.select(false), "on click"); } else if (this.Document.type === DocumentType.BUTTON) { UndoManager.RunInBatch(() => ScriptBox.EditButtonScript("On Button Clicked ...", this.props.Document, "onClick", e.clientX, e.clientY), "on button click"); } else if (this.Document.isButton) { @@ -633,13 +637,23 @@ export class DocumentView extends DocComponent(Docu if (custom) { DocumentView.makeNativeViewClicked(this.props.Document); + const imgView = Cast(Doc.UserDoc().iconView, Doc, null); + const iconImgView = Cast(Doc.UserDoc().iconImageView, Doc, null); + const iconColView = Cast(Doc.UserDoc().iconColView, Doc, null); + const iconViews = [imgView, iconImgView, iconColView]; + const expandingButtons = DocListCast(Cast(Doc.UserDoc().expandingButtons, Doc, null)?.data); + const allTemplates = iconViews.concat(expandingButtons); let foundLayout: Opt; - DocListCast(Cast(Doc.UserDoc().expandingButtons, Doc, null)?.data)?.concat([Cast(Doc.UserDoc().iconView, Doc, null)]). - map(btnDoc => (btnDoc.dragFactory as Doc) || btnDoc).filter(doc => doc.isTemplateDoc).forEach(tempDoc => { - if (StrCast(tempDoc.title) === layout) { - foundLayout = tempDoc; - } - }); + allTemplates.map(btnDoc => (btnDoc.dragFactory as Doc) || btnDoc).filter(doc => doc.isTemplateDoc).forEach(tempDoc => { + if (StrCast(tempDoc.title) === this.props.Document.type + "_" + layout) { + foundLayout = tempDoc; + } + }); + !foundLayout && allTemplates.map(btnDoc => (btnDoc.dragFactory as Doc) || btnDoc).filter(doc => doc.isTemplateDoc).forEach(tempDoc => { + if (StrCast(tempDoc.title) === layout) { + foundLayout = tempDoc; + } + }); DocumentView. makeCustomViewClicked(this.props.Document, this.props.DataDoc, Docs.Create.StackingDocument, layout, foundLayout); } else { diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index e5848614c..6ae32a1d6 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -258,7 +258,7 @@ export class ImageBox extends DocAnnotatableComponent 0.05 || imgPath !== cachedImgPath) { (!this.layoutDoc.isTemplateDoc || this.dataDoc !== this.layoutDoc) && requestImageSize(imgPath).then((inquiredSize: any) => { const rotation = NumCast(this.dataDoc[this.props.fieldKey + "-rotation"]) % 180; const rotatedNativeSize = rotation === 90 || rotation === 270 ? { height: inquiredSize.width, width: inquiredSize.height } : inquiredSize; diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index 4a6ff8e42..c7caa853a 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -792,7 +792,7 @@ export namespace Doc { export function setNativeView(doc: any) { const prevLayout = StrCast(doc.layoutKey).split("_")[1]; const deiconify = prevLayout === "icon" && StrCast(doc.deiconifyLayout) ? "layout_" + StrCast(doc.deiconifyLayout) : ""; - doc.deiconifyLayout = undefined; + prevLayout === "icon" && (doc.deiconifyLayout = undefined); if (StrCast(doc.title).endsWith("_" + prevLayout) && deiconify) doc.title = StrCast(doc.title).replace("_" + prevLayout, deiconify); else doc.title = undefined; doc.layoutKey = deiconify || "layout"; diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 5d93f208a..15f626af4 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -11,7 +11,7 @@ import { listSpec } from "../../../new_fields/Schema"; import { ScriptField, ComputedField } from "../../../new_fields/ScriptField"; import { Cast, PromiseValue, StrCast } from "../../../new_fields/Types"; import { Utils } from "../../../Utils"; -import { nullAudio } from "../../../new_fields/URLField"; +import { nullAudio, ImageField } from "../../../new_fields/URLField"; import { DragManager } from "../../../client/util/DragManager"; import { InkingControl } from "../../../client/views/InkingControl"; import { Scripting } from "../../../client/util/Scripting"; @@ -194,7 +194,7 @@ export class CurrentUserUtils { }); return Docs.Create.ButtonDocument({ - _width: 35, _height: 25, title: "Tools", fontSize: 10, targetContainer: sidebarContainer, + _width: 35, _height: 25, title: "Tools", fontSize: 10, targetContainer: sidebarContainer, dontSelect: true, letterSpacing: "0px", textTransform: "unset", borderRounding: "5px 5px 0px 0px", boxShadow: "3px 3px 0px rgb(34, 34, 34)", sourcePanel: Docs.Create.StackingDocument([dragCreators, color], { _width: 500, lockedPosition: true, _chromeStatus: "disabled", title: "tools stack" @@ -220,7 +220,7 @@ export class CurrentUserUtils { }); return Docs.Create.ButtonDocument({ - _width: 50, _height: 25, title: "Library", fontSize: 10, + _width: 50, _height: 25, title: "Library", fontSize: 10, dontSelect: true, letterSpacing: "0px", textTransform: "unset", borderRounding: "5px 5px 0px 0px", boxShadow: "3px 3px 0px rgb(34, 34, 34)", sourcePanel: Docs.Create.TreeDocument([doc.workspaces as Doc, doc.documents as Doc, Docs.Prototypes.MainLinkDocument(), doc, doc.recentlyClosed as Doc], { title: "Library", _xMargin: 5, _yMargin: 5, _gridGap: 5, forceActive: true, dropAction: "alias", lockedPosition: true, boxShadow: "0 0", dontRegisterChildren: true @@ -233,7 +233,7 @@ export class CurrentUserUtils { // setup the Search button which will display the search panel. static setupSearchPanel(sidebarContainer: Doc) { return Docs.Create.ButtonDocument({ - _width: 50, _height: 25, title: "Search", fontSize: 10, + _width: 50, _height: 25, title: "Search", fontSize: 10, dontSelect: true, letterSpacing: "0px", textTransform: "unset", borderRounding: "5px 5px 0px 0px", boxShadow: "3px 3px 0px rgb(34, 34, 34)", sourcePanel: Docs.Create.QueryDocument({ title: "search stack", ignoreClick: true @@ -275,9 +275,15 @@ export class CurrentUserUtils { descriptionTemplate.isTemplateDoc = makeTemplate(descriptionTemplate, true, "descriptionView"); const iconDoc = Docs.Create.TextDocument("", { title: "icon", _width: 150, _height: 30, isTemplateDoc: true, onClick: ScriptField.MakeScript("setNativeView(this)") }); - Doc.GetProto(iconDoc).data = new RichTextField('{"doc":{"type":"doc","content":[{"type":"paragraph","attrs":{"align":null,"color":null,"id":null,"indent":null,"inset":null,"lineSpacing":null,"paddingBottom":null,"paddingTop":null},"content":[{"type":"dashField","attrs":{"fieldKey":"title","docid":""}}]}]},"selection":{"type":"text","anchor":2,"head":2},"storedMarks":[]}', ""); + Doc.GetProto(iconDoc).icon = new RichTextField('{"doc":{"type":"doc","content":[{"type":"paragraph","attrs":{"align":null,"color":null,"id":null,"indent":null,"inset":null,"lineSpacing":null,"paddingBottom":null,"paddingTop":null},"content":[{"type":"dashField","attrs":{"fieldKey":"title","docid":""}}]}]},"selection":{"type":"text","anchor":2,"head":2},"storedMarks":[]}', ""); doc.isTemplateDoc = makeTemplate(iconDoc); doc.iconView = new PrefetchProxy(iconDoc); + const imgIconDoc = Docs.Create.ImageDocument("http://www.cs.brown.edu/~bcz/face.gif", { title: "data", _width: 50, isTemplateDoc: true, onClick: ScriptField.MakeScript("setNativeView(this)") }); + doc.isTemplateDoc = makeTemplate(imgIconDoc, true, "image_icon"); + doc.iconImageView = new PrefetchProxy(imgIconDoc); + const colIconDoc = Docs.Create.TreeDocument([], { title: "data", _width: 180, _height: 80, isTemplateDoc: true, onClick: ScriptField.MakeScript("setNativeView(this)") }); + doc.isTemplateDoc = makeTemplate(colIconDoc, true, "collection_icon"); + doc.iconColView = new PrefetchProxy(colIconDoc); doc.undoBtn = Docs.Create.FontIconDocument( { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onClick: ScriptField.MakeScript("undo()"), removeDropProperties: new List(["dropAction"]), title: "undo button", icon: "undo-alt" }); -- cgit v1.2.3-70-g09d2 From d466e368ad164347f82a160e7088540a78c230f6 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Tue, 10 Mar 2020 11:07:59 -0400 Subject: made stacking view hide edit/view button unless selected. get rid of columns with no documens when hideHeadings is set. --- src/client/views/collections/CollectionStackingView.tsx | 12 ++++++++++-- src/server/authentication/models/current_user_utils.ts | 4 ++-- 2 files changed, 12 insertions(+), 4 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index 3f7f0a352..a936582c3 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -100,6 +100,14 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { changed = true; } }); + // remove all empty columns if hideHeadings is set + if (this.props.Document.hideHeadings) { + Array.from(fields.keys()).filter(key => !fields.get(key)!.length).map(header => { + fields.delete(header); + sectionHeaders.splice(sectionHeaders.indexOf(header), 1); + changed = true; + }) + } changed && setTimeout(action(() => { if (this.sectionHeaders) { this.sectionHeaders.length = 0; this.sectionHeaders.push(...sectionHeaders); } }), 0); return fields; } @@ -276,7 +284,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { } }); } - headings = () => Array.from(this.Sections.keys()); + headings = () => Array.from(this.Sections); sectionStacking = (heading: SchemaHeaderField | undefined, docList: Doc[]) => { const key = this.pivotField; let type: "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" | undefined = undefined; @@ -407,7 +415,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { style={{ width: !this.isStackingView ? "100%" : this.columnWidth / this.numGroupColumns - 10, marginTop: 10 }}>
    } - {this.props.Document._chromeStatus !== 'disabled' ? Date: Tue, 10 Mar 2020 11:31:55 -0400 Subject: fixed buttons so they don't select --- src/server/authentication/models/current_user_utils.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 0fbc596af..a2be93d73 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -83,7 +83,7 @@ export class CurrentUserUtils { return docProtoData.filter(d => !buttons || !buttons.includes(d.title)).map(data => Docs.Create.FontIconDocument({ _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: data.click ? "copy" : undefined, title: data.title, icon: data.icon, ignoreClick: data.ignoreClick, onDragStart: data.drag ? ScriptField.MakeFunction(data.drag) : undefined, onClick: data.click ? ScriptField.MakeScript(data.click) : undefined, - ischecked: data.ischecked ? ComputedField.MakeFunction(data.ischecked) : undefined, activePen: data.activePen, + ischecked: data.ischecked ? ComputedField.MakeFunction(data.ischecked) : undefined, activePen: data.activePen, dontSelect: true, backgroundColor: data.backgroundColor, removeDropProperties: new List(["dropAction"]), dragFactory: data.dragFactory, })); } -- cgit v1.2.3-70-g09d2 From dafd2ce66e28e91408c76712fdc5710a835aa388 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Wed, 11 Mar 2020 22:52:36 -0400 Subject: removed scrubber tool which isn't being used anymore (audiobox has its own scrubber) --- src/client/views/InkingControl.tsx | 1 - .../collectionFreeForm/CollectionFreeFormView.tsx | 21 +-------------------- src/new_fields/InkField.ts | 1 - .../authentication/models/current_user_utils.ts | 2 -- 4 files changed, 1 insertion(+), 24 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/views/InkingControl.tsx b/src/client/views/InkingControl.tsx index 5cd3c265d..645c7fa54 100644 --- a/src/client/views/InkingControl.tsx +++ b/src/client/views/InkingControl.tsx @@ -85,7 +85,6 @@ export class InkingControl { Scripting.addGlobal(function activatePen(pen: any, width: any, color: any) { InkingControl.Instance.switchTool(pen ? InkTool.Pen : InkTool.None); InkingControl.Instance.switchWidth(width); InkingControl.Instance.updateSelectedColor(color); }); Scripting.addGlobal(function activateBrush(pen: any, width: any, color: any) { InkingControl.Instance.switchTool(pen ? InkTool.Highlighter : InkTool.None); InkingControl.Instance.switchWidth(width); InkingControl.Instance.updateSelectedColor(color); }); Scripting.addGlobal(function activateEraser(pen: any) { return InkingControl.Instance.switchTool(pen ? InkTool.Eraser : InkTool.None); }); -Scripting.addGlobal(function activateScrubber(pen: any) { return InkingControl.Instance.switchTool(pen ? InkTool.Scrubber : InkTool.None); }); Scripting.addGlobal(function activateStamp(pen: any) { return InkingControl.Instance.switchTool(pen ? InkTool.Stamp : InkTool.None); }); Scripting.addGlobal(function deactivateInk() { return InkingControl.Instance.switchTool(InkTool.None); }); Scripting.addGlobal(function setInkWidth(width: any) { return InkingControl.Instance.switchWidth(width); }); diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 7adafea0e..fd679b7b2 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -330,31 +330,12 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { this._lastX = e.pageX; this._lastY = e.pageY; } - // eraser or scrubber plus anything else mode + // eraser plus anything else mode else { e.stopPropagation(); e.preventDefault(); } } - // if (e.button === 0 && !e.shiftKey && !e.altKey && !e.ctrlKey && this.props.active(true)) { - // document.removeEventListener("pointermove", this.onPointerMove); - // document.removeEventListener("pointerup", this.onPointerUp); - // document.addEventListener("pointermove", this.onPointerMove); - // document.addEventListener("pointerup", this.onPointerUp); - // if (InkingControl.Instance.selectedTool === InkTool.None) { - // this._lastX = e.pageX; - // this._lastY = e.pageY; - // } - // else { - // e.stopPropagation(); - // e.preventDefault(); - - // if (InkingControl.Instance.selectedTool !== InkTool.Eraser && InkingControl.Instance.selectedTool !== InkTool.Scrubber) { - // let point = this.getTransform().transformPoint(e.pageX, e.pageY); - // this._points.push({ x: point[0], y: point[1] }); - // } - // } - // } } @action diff --git a/src/new_fields/InkField.ts b/src/new_fields/InkField.ts index 4a44b4f55..bb93de5ac 100644 --- a/src/new_fields/InkField.ts +++ b/src/new_fields/InkField.ts @@ -8,7 +8,6 @@ export enum InkTool { Pen, Highlighter, Eraser, - Scrubber, Stamp } diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index a2be93d73..d1f68ba49 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -77,7 +77,6 @@ export class CurrentUserUtils { { title: "use highlighter", icon: "highlighter", click: 'activateBrush(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this,20,this.backgroundColor)', backgroundColor: "yellow", ischecked: `sameDocs(this.activePen.pen, this)`, activePen: doc }, { title: "use stamp", icon: "stamp", click: 'activateStamp(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this)', backgroundColor: "orange", ischecked: `sameDocs(this.activePen.pen, this)`, activePen: doc }, { title: "use eraser", icon: "eraser", click: 'activateEraser(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "pink", activePen: doc }, - { title: "use scrubber", icon: "eraser", click: 'activateScrubber(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "green", activePen: doc }, { title: "use drag", icon: "mouse-pointer", click: 'deactivateInk();this.activePen.pen = this;', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "white", activePen: doc }, ]; return docProtoData.filter(d => !buttons || !buttons.includes(d.title)).map(data => Docs.Create.FontIconDocument({ @@ -115,7 +114,6 @@ export class CurrentUserUtils { { title: "use pen", icon: "pen-nib", click: 'activatePen(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this,2, this.backgroundColor)', backgroundColor: "blue", ischecked: `sameDocs(this.activePen.pen, this)`, activePen: doc }, { title: "use highlighter", icon: "highlighter", click: 'activateBrush(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this,20,this.backgroundColor)', backgroundColor: "yellow", ischecked: `sameDocs(this.activePen.pen, this)`, activePen: doc }, { title: "use eraser", icon: "eraser", click: 'activateEraser(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "pink", activePen: doc }, - { title: "use scrubber", icon: "eraser", click: 'activateScrubber(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "green", activePen: doc }, { title: "use drag", icon: "mouse-pointer", click: 'deactivateInk();this.activePen.pen = this;', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "white", activePen: doc }, // { title: "draw", icon: "pen-nib", click: 'switchMobileView(setupMobileInkingDoc, renderMobileInking, onSwitchMobileInking);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "red", activePen: doc }, { title: "upload", icon: "upload", click: 'switchMobileView(setupMobileUploadDoc, renderMobileUpload, onSwitchMobileUpload);', backgroundColor: "orange" }, -- cgit v1.2.3-70-g09d2 From 85a67ff30d86fa51b4534f717d3857aa23b732d1 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 19 Mar 2020 12:04:32 -0400 Subject: added screen capture doc --- src/client/documents/DocumentTypes.ts | 3 +- src/client/documents/Documents.ts | 9 + src/client/views/collections/CollectionSubView.tsx | 2 +- src/client/views/nodes/DocumentContentsView.tsx | 3 +- src/client/views/nodes/ImageBox.tsx | 27 ++- src/client/views/nodes/ScreenshotBox.scss | 46 +++++ src/client/views/nodes/ScreenshotBox.tsx | 193 +++++++++++++++++++++ src/client/views/nodes/VideoBox.tsx | 17 +- src/client/views/nodes/WebBox.scss | 7 +- src/client/views/nodes/WebBox.tsx | 9 +- .../authentication/models/current_user_utils.ts | 3 +- 11 files changed, 296 insertions(+), 23 deletions(-) create mode 100644 src/client/views/nodes/ScreenshotBox.scss create mode 100644 src/client/views/nodes/ScreenshotBox.tsx (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/documents/DocumentTypes.ts b/src/client/documents/DocumentTypes.ts index e3ce8e798..5ec1cfdb4 100644 --- a/src/client/documents/DocumentTypes.ts +++ b/src/client/documents/DocumentTypes.ts @@ -27,5 +27,6 @@ export enum DocumentType { DOCULINK = "doculink", PDFANNO = "pdfanno", INK = "ink", - DOCUMENT = "document" + DOCUMENT = "document", + SCREENSHOT = "screenshot", } \ No newline at end of file diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 131a48a2b..b5cffaddd 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -58,6 +58,7 @@ import { MessageStore } from "../../server/Message"; import { ContextMenuProps } from "../views/ContextMenuItem"; import { ContextMenu } from "../views/ContextMenu"; import { LinkBox } from "../views/nodes/LinkBox"; +import { ScreenshotBox } from "../views/nodes/ScreenshotBox"; const requestImageSize = require('../util/request-image-size'); const path = require('path'); @@ -277,6 +278,10 @@ export namespace Docs { [DocumentType.INK, { layout: { view: InkingStroke, dataField: data }, options: { backgroundColor: "transparent" } + }], + [DocumentType.SCREENSHOT, { + layout: { view: ScreenshotBox, dataField: data }, + options: {} }] ]); @@ -522,6 +527,10 @@ export namespace Docs { return InstanceFromProto(Prototypes.get(DocumentType.WEBCAM), "", options); } + export function ScreenshotDocument(url: string, options: DocumentOptions = {}) { + return InstanceFromProto(Prototypes.get(DocumentType.SCREENSHOT), "", options); + } + export function AudioDocument(url: string, options: DocumentOptions = {}) { const instance = InstanceFromProto(Prototypes.get(DocumentType.AUDIO), new AudioField(new URL(url)), options); Doc.GetProto(instance).backgroundColor = ComputedField.MakeFunction("this._audioState === 'playing' ? 'green':'gray'"); diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index 2d6777a4e..97177855f 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -316,7 +316,7 @@ export function CollectionSubView(schemaCtor: (doc: Doc) => T) { const item = e.dataTransfer.items[i]; if (item.kind === "string" && item.type.includes("uri")) { const stringContents = await new Promise(resolve => item.getAsString(resolve)); - const type = (await rp.head(Utils.CorsProxy(stringContents)))["content-type"]; + const type = "html";// (await rp.head(Utils.CorsProxy(stringContents)))["content-type"]; if (type) { const doc = await Docs.Get.DocumentFromType(type, stringContents, options); doc && generatedDocuments.push(doc); diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index f121ba3e0..239f414fd 100644 --- a/src/client/views/nodes/DocumentContentsView.tsx +++ b/src/client/views/nodes/DocumentContentsView.tsx @@ -29,6 +29,7 @@ import { ColorBox } from "./ColorBox"; import { DashWebRTCVideo } from "../webcam/DashWebRTCVideo"; import { DocuLinkBox } from "./DocuLinkBox"; import { PresElementBox } from "../presentationview/PresElementBox"; +import { ScreenshotBox } from "./ScreenshotBox"; import { VideoBox } from "./VideoBox"; import { WebBox } from "./WebBox"; import { InkingStroke } from "../InkingStroke"; @@ -99,7 +100,7 @@ export class DocumentContentsView extends React.Component Utils.CopyText(field.url.href), icon: "expand-arrows-alt" }); funcs.push({ description: "Rotate", event: this.rotate, icon: "expand-arrows-alt" }); funcs.push({ - description: "Reset Native Dimensions", event: action(() => { + description: "Reset Native Dimensions", event: action(async () => { const curNW = NumCast(this.dataDoc[this.props.fieldKey + "-nativeWidth"]); const curNH = NumCast(this.dataDoc[this.props.fieldKey + "-nativeHeight"]); if (this.props.PanelWidth() / this.props.PanelHeight() > curNW / curNH) { diff --git a/src/client/views/nodes/ScreenshotBox.scss b/src/client/views/nodes/ScreenshotBox.scss new file mode 100644 index 000000000..4aaccb472 --- /dev/null +++ b/src/client/views/nodes/ScreenshotBox.scss @@ -0,0 +1,46 @@ +.screenshotBox { + pointer-events: all; + transform-origin: top left; + background: white; + color: black; + // .screenshotBox-viewer { + // opacity: 0.99; // hack! overcomes some kind of Chrome weirdness where buttons (e.g., snapshot) disappear at some point as the video is resized larger + // } + // .inkingCanvas-paths-markers { + // opacity : 0.4; // we shouldn't have to do this, but since chrome crawls to a halt with z-index unset in videoBox-content, this is a workaround + // } +} + +.screenshotBox-content, .screenshotBox-content-interactive, .screenshotBox-cont-fullScreen { + width: 100%; + z-index: -1; // 0; // logically this should be 0 (or unset) which would give us transparent brush strokes over videos. However, this makes Chrome crawl to a halt + position: absolute; +} + +.screenshotBox-content, .screenshotBox-content-interactive, .screenshotBox-content-fullScreen { + height: Auto; +} + +.screenshotBox-content-interactive, .screenshotBox-content-fullScreen { + pointer-events: all; +} + +.screenshotBox-snapshot{ + color : white; + top :25px; + right : 25px; + position: absolute; + background-color:rgba(50, 50, 50, 0.2); + transform-origin: left top; + pointer-events:all; +} + +.screenshotBox-recorder{ + color : white; + top :25px; + right : 50px; + position: absolute; + background-color:rgba(50, 50, 50, 0.2); + transform-origin: left top; + pointer-events:all; +} diff --git a/src/client/views/nodes/ScreenshotBox.tsx b/src/client/views/nodes/ScreenshotBox.tsx new file mode 100644 index 000000000..de9e521f6 --- /dev/null +++ b/src/client/views/nodes/ScreenshotBox.tsx @@ -0,0 +1,193 @@ +import React = require("react"); +import { library } from "@fortawesome/fontawesome-svg-core"; +import { faVideo } from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { action, computed, IReactionDisposer, observable, runInAction } from "mobx"; +import { observer } from "mobx-react"; +import * as rp from 'request-promise'; +import { documentSchema, positionSchema } from "../../../new_fields/documentSchemas"; +import { makeInterface } from "../../../new_fields/Schema"; +import { ScriptField } from "../../../new_fields/ScriptField"; +import { Cast, StrCast } from "../../../new_fields/Types"; +import { VideoField } from "../../../new_fields/URLField"; +import { emptyFunction, returnFalse, returnOne, Utils } from "../../../Utils"; +import { Docs, DocUtils } from "../../documents/Documents"; +import { CollectionFreeFormView } from "../collections/collectionFreeForm/CollectionFreeFormView"; +import { ContextMenu } from "../ContextMenu"; +import { ContextMenuProps } from "../ContextMenuItem"; +import { DocAnnotatableComponent } from "../DocComponent"; +import { InkingControl } from "../InkingControl"; +import { FieldView, FieldViewProps } from './FieldView'; +import "./ScreenshotBox.scss"; +const path = require('path'); + +type ScreenshotDocument = makeInterface<[typeof documentSchema, typeof positionSchema]>; +const ScreenshotDocument = makeInterface(documentSchema, positionSchema); + +library.add(faVideo); + +@observer +export class ScreenshotBox extends DocAnnotatableComponent(ScreenshotDocument) { + private _reactionDisposer?: IReactionDisposer; + private _videoRef: HTMLVideoElement | null = null; + public static LayoutString(fieldKey: string) { return FieldView.LayoutString(ScreenshotBox, fieldKey); } + + public get player(): HTMLVideoElement | null { + return this._videoRef; + } + + videoLoad = () => { + const aspect = this.player!.videoWidth / this.player!.videoHeight; + const nativeWidth = (this.Document._nativeWidth || 0); + const nativeHeight = (this.Document._nativeHeight || 0); + if (!nativeWidth || !nativeHeight) { + if (!this.Document._nativeWidth) this.Document._nativeWidth = this.player!.videoWidth; + this.Document._nativeHeight = (this.Document._nativeWidth || 0) / aspect; + this.Document._height = (this.Document._width || 0) / aspect; + } + if (!this.Document.duration) this.Document.duration = this.player!.duration; + } + + @action public Snapshot() { + const width = this.Document._width || 0; + const height = this.Document._height || 0; + const canvas = document.createElement('canvas'); + canvas.width = 640; + canvas.height = 640 * (this.Document._nativeHeight || 0) / (this.Document._nativeWidth || 1); + const ctx = canvas.getContext('2d');//draw image to canvas. scale to target dimensions + if (ctx) { + ctx.rect(0, 0, canvas.width, canvas.height); + ctx.fillStyle = "blue"; + ctx.fill(); + this._videoRef && ctx.drawImage(this._videoRef, 0, 0, canvas.width, canvas.height); + } + + if (this._videoRef) { + //convert to desired file format + const dataUrl = canvas.toDataURL('image/png'); // can also use 'image/png' + // if you want to preview the captured image, + const filename = path.basename(encodeURIComponent("screenshot" + Utils.GenerateGuid().replace(/\..*$/, "").replace(" ", "_"))); + ScreenshotBox.convertDataUri(dataUrl, filename).then(returnedFilename => { + setTimeout(() => { + if (returnedFilename) { + const imageSummary = Docs.Create.ImageDocument(Utils.prepend(returnedFilename), { + x: (this.Document.x || 0) + width, y: (this.Document.y || 0), + _width: 150, _height: height / width * 150, title: "--screenshot--" + }); + this.props.addDocument?.(imageSummary); + } + }, 500); + }); + } + } + + componentDidMount() { + } + + componentWillUnmount() { + this._reactionDisposer && this._reactionDisposer(); + } + + @action + setVideoRef = (vref: HTMLVideoElement | null) => { + this._videoRef = vref; + } + + public static async convertDataUri(imageUri: string, returnedFilename: string) { + try { + const posting = Utils.prepend("/uploadURI"); + const returnedUri = await rp.post(posting, { + body: { + uri: imageUri, + name: returnedFilename + }, + json: true, + }); + return returnedUri; + + } catch (e) { + console.log(e); + } + } + @observable _screenCapture = false; + specificContextMenu = (e: React.MouseEvent): void => { + const field = Cast(this.dataDoc[this.props.fieldKey], VideoField); + if (field) { + const url = field.url.href; + const subitems: ContextMenuProps[] = []; + subitems.push({ description: "Take Snapshot", event: () => this.Snapshot(), icon: "expand-arrows-alt" }); + subitems.push({ + description: "Screen Capture", event: (async () => { + runInAction(() => this._screenCapture = !this._screenCapture); + this._videoRef!.srcObject = !this._screenCapture ? undefined : await (navigator.mediaDevices as any).getDisplayMedia({ video: true }); + }), icon: "expand-arrows-alt" + }); + ContextMenu.Instance.addItem({ description: "Screenshot Funcs...", subitems: subitems, icon: "video" }); + } + } + + @computed get content() { + const interactive = InkingControl.Instance.selectedTool || !this.props.isSelected() ? "" : "-interactive"; + const style = "videoBox-content" + interactive; + return ; + } + + toggleRecording = action(async () => { + this._screenCapture = !this._screenCapture; + this._videoRef!.srcObject = !this._screenCapture ? undefined : await (navigator.mediaDevices as any).getDisplayMedia({ video: true }); + }) + + private get uIButtons() { + return ([ +
    + +
    , +
    + +
    ]); + } + + onSnapshot = (e: React.PointerEvent) => { + this.Snapshot(); + e.stopPropagation(); + e.preventDefault(); + } + + + contentFunc = () => [this.content]; + render() { + return (
    +
    + + {this.contentFunc} + +
    + {this.uIButtons} +
    ); + } +} \ No newline at end of file diff --git a/src/client/views/nodes/VideoBox.tsx b/src/client/views/nodes/VideoBox.tsx index 439f2d85f..24b66d8f7 100644 --- a/src/client/views/nodes/VideoBox.tsx +++ b/src/client/views/nodes/VideoBox.tsx @@ -195,6 +195,7 @@ export class VideoBox extends DocAnnotatableComponent { const field = Cast(this.dataDoc[this.props.fieldKey], VideoField); if (field) { @@ -203,6 +204,12 @@ export class VideoBox extends DocAnnotatableComponent { Utils.CopyText(url); }, icon: "expand-arrows-alt" }); subitems.push({ description: "Toggle Show Controls", event: action(() => VideoBox._showControls = !VideoBox._showControls), icon: "expand-arrows-alt" }); subitems.push({ description: "Take Snapshot", event: () => this.Snapshot(), icon: "expand-arrows-alt" }); + subitems.push({ + description: "Screen Capture", event: (async () => { + runInAction(() => this._screenCapture = !this._screenCapture); + this._videoRef!.srcObject = !this._screenCapture ? undefined : await (navigator.mediaDevices as any).getDisplayMedia({ video: true }); + }), icon: "expand-arrows-alt" + }); ContextMenu.Instance.addItem({ description: "Video Funcs...", subitems: subitems, icon: "video" }); } } @@ -212,8 +219,14 @@ export class VideoBox extends DocAnnotatableComponentLoading
    : -
    ); } onSnapshot = (e: React.PointerEvent) => { @@ -187,7 +188,7 @@ export class ScreenshotBox extends DocAnnotatableComponent
    - {this.uIButtons} + {this.active() ? this.uIButtons : (null)}
    ); } } \ No newline at end of file diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index ea7b91b23..31588bf82 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -222,7 +222,7 @@ export class CurrentUserUtils { _width: 50, _height: 25, title: "Library", fontSize: 10, dontSelect: true, letterSpacing: "0px", textTransform: "unset", borderRounding: "5px 5px 0px 0px", boxShadow: "3px 3px 0px rgb(34, 34, 34)", sourcePanel: Docs.Create.TreeDocument([doc.workspaces as Doc, doc.documents as Doc, Docs.Prototypes.MainLinkDocument(), doc, doc.recentlyClosed as Doc], { - title: "Library", _xMargin: 5, _yMargin: 5, _gridGap: 5, forceActive: true, dropAction: "alias", lockedPosition: true, boxShadow: "0 0", dontRegisterChildren: true + title: "Library", _xMargin: 5, _yMargin: 5, _gridGap: 5, forceActive: true, childDropAction: "place", lockedPosition: true, boxShadow: "0 0", dontRegisterChildren: true }), targetContainer: sidebarContainer, onClick: ScriptField.MakeScript("this.targetContainer.proto = this.sourcePanel;") -- cgit v1.2.3-70-g09d2 From 786572f3cd674459f55b7f66e8eb257026f373ef Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Mon, 23 Mar 2020 21:24:50 -0400 Subject: fixed RichTextMenu to not obscure selection. fixed templateMenu to display a TreeView document of options. fixed resize in docDecorations for dragging corners other than bottom-right. --- src/client/util/DropConverter.ts | 2 +- src/client/views/DocumentButtonBar.tsx | 4 +- src/client/views/DocumentDecorations.scss | 3 + src/client/views/DocumentDecorations.tsx | 6 +- src/client/views/TemplateMenu.tsx | 94 ++++++++++++++++++---- .../views/collections/CollectionDockingView.tsx | 27 +++++-- .../views/collections/CollectionLinearView.tsx | 20 ++--- .../views/collections/CollectionTreeView.scss | 1 + .../views/collections/CollectionTreeView.tsx | 7 +- .../views/collections/ParentDocumentSelector.tsx | 22 ++--- .../collections/collectionFreeForm/MarqueeView.tsx | 12 ++- src/client/views/nodes/DocumentView.tsx | 15 ++-- src/client/views/nodes/FormattedTextBox.tsx | 25 ++++-- src/client/views/search/SearchItem.tsx | 2 +- src/new_fields/Doc.ts | 2 - src/new_fields/ScriptField.ts | 4 +- src/new_fields/util.ts | 1 - .../authentication/models/current_user_utils.ts | 16 +++- 18 files changed, 189 insertions(+), 74 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/util/DropConverter.ts b/src/client/util/DropConverter.ts index 861cde5de..a6a43d06a 100644 --- a/src/client/util/DropConverter.ts +++ b/src/client/util/DropConverter.ts @@ -49,7 +49,7 @@ export function convertDropDataToButtons(data: DragManager.DocumentDragData) { (layoutDoc.layout instanceof Doc) && !data.userDropAction; } layoutDoc.isTemplateDoc = true; - dbox = Docs.Create.FontIconDocument({ _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, backgroundColor: StrCast(doc.backgroundColor), title: "Custom", icon: layoutDoc.isTemplateDoc ? "font" : "bolt" }); + dbox = Docs.Create.FontIconDocument({ _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, backgroundColor: StrCast(doc.backgroundColor), title: StrCast(layoutDoc.title), icon: layoutDoc.isTemplateDoc ? "font" : "bolt" }); dbox.dragFactory = layoutDoc; dbox.removeDropProperties = doc.removeDropProperties instanceof ObjectField ? ObjectField.MakeCopy(doc.removeDropProperties) : undefined; dbox.onDragStart = ScriptField.MakeFunction('getCopy(this.dragFactory, true)'); diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx index 23875fa33..8a33232b4 100644 --- a/src/client/views/DocumentButtonBar.tsx +++ b/src/client/views/DocumentButtonBar.tsx @@ -108,7 +108,7 @@ export class DocumentButtonBar extends React.Component<{ views: (DocumentView | this._pullColorAnimating = false; }); - get view0() { return this.props.views && this.props.views.length ? this.props.views[0] : undefined; } + get view0() { return this.props.views?.[0]; } @action onLinkButtonMoved = (e: PointerEvent): void => { @@ -250,7 +250,7 @@ export class DocumentButtonBar extends React.Component<{ views: (DocumentView | @computed get contextButton() { - return !this.view0 ? (null) : v).map(v => v as DocumentView)} Document={this.view0.props.Document} addDocTab={(doc, where) => { + return !this.view0 ? (null) : { where === "onRight" ? CollectionDockingView.AddRightSplit(doc) : this.props.stack ? CollectionDockingView.Instance.AddTab(this.props.stack, doc) : this.view0?.props.addDocTab(doc, "onRight"); diff --git a/src/client/views/DocumentDecorations.scss b/src/client/views/DocumentDecorations.scss index 8d6002f8f..353520026 100644 --- a/src/client/views/DocumentDecorations.scss +++ b/src/client/views/DocumentDecorations.scss @@ -80,6 +80,7 @@ $linkGap : 3px; #documentDecorations-topLeftResizer, #documentDecorations-bottomRightResizer { cursor: nwse-resize; + background: dimGray; } #documentDecorations-bottomRightResizer { @@ -89,6 +90,7 @@ $linkGap : 3px; #documentDecorations-topRightResizer, #documentDecorations-bottomLeftResizer { cursor: nesw-resize; + background: dimGray; } #documentDecorations-topResizer, @@ -158,6 +160,7 @@ $linkGap : 3px; padding-top: 5px; width: $MINIMIZED_ICON_SIZE; height: $MINIMIZED_ICON_SIZE; + max-height: 20px; } .documentDecorations-background { diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index c4abc935f..ff72592d8 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -266,7 +266,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> let dist = Math.sqrt((e.clientX - down[0]) * (e.clientX - down[0]) + (e.clientY - down[1]) * (e.clientY - down[1])); dist = dist < 3 ? 0 : dist; SelectionManager.SelectedDocuments().map(dv => dv.props.Document).map(doc => doc.layout instanceof Doc ? doc.layout : doc.isTemplateForField ? doc : Doc.GetProto(doc)). - map(d => d.borderRounding = `${Math.max(0, dist)}px`); + map(d => d.borderRounding = `${Math.max(0, dist)}%`); return false; } @@ -330,6 +330,10 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> const width = (layoutDoc._width || 0); const height = (layoutDoc._height || (nheight / nwidth * width)); const scale = element.props.ScreenToLocalTransform().Scale * element.props.ContentScaling(); + if (nwidth && nheight) { + if (Math.abs(dW) > Math.abs(dH)) dH = dW * nheight / nwidth; + else dW = dH * nwidth / nheight; + } const actualdW = Math.max(width + (dW * scale), 20); const actualdH = Math.max(height + (dH * scale), 20); doc.x = (doc.x || 0) + dX * (actualdW - width); diff --git a/src/client/views/TemplateMenu.tsx b/src/client/views/TemplateMenu.tsx index 5029b4074..cf6ce2c6f 100644 --- a/src/client/views/TemplateMenu.tsx +++ b/src/client/views/TemplateMenu.tsx @@ -1,4 +1,4 @@ -import { action, observable, runInAction, ObservableSet } from "mobx"; +import { action, observable, runInAction, ObservableSet, trace, computed } from "mobx"; import { observer } from "mobx-react"; import { SelectionManager } from "../util/SelectionManager"; import { undoBatch } from "../util/UndoManager"; @@ -7,8 +7,13 @@ import { DocumentView } from "./nodes/DocumentView"; import { Template } from "./Templates"; import React = require("react"); import { Doc, DocListCast } from "../../new_fields/Doc"; +import { Docs, } from "../documents/Documents"; import { StrCast, Cast } from "../../new_fields/Types"; -import { CurrentUserUtils } from "../../server/authentication/models/current_user_utils"; +import { CollectionTreeView } from "./collections/CollectionTreeView"; +import { returnTrue, emptyFunction, returnFalse, returnOne, emptyPath } from "../../Utils"; +import { Transform } from "../util/Transform"; +import { ScriptField, ComputedField } from "../../new_fields/ScriptField"; +import { Scripting } from "../util/Scripting"; @observer class TemplateToggle extends React.Component<{ template: Template, checked: boolean, toggle: (event: React.ChangeEvent, template: Template) => void }> { @@ -50,7 +55,10 @@ export class TemplateMenu extends React.Component { @observable private _hidden: boolean = true; toggleLayout = (e: React.ChangeEvent, layout: string): void => { - this.props.docViews.map(dv => dv.switchViews(e.target.checked, layout));//.setCustomView(e.target.checked, layout)); + this.props.docViews.map(dv => dv.switchViews(e.target.checked, layout)); + } + toggleDefault = (e: React.ChangeEvent): void => { + this.props.docViews.map(dv => dv.switchViews(false, "layout")); } toggleFloat = (e: React.ChangeEvent): void => { @@ -94,27 +102,81 @@ export class TemplateMenu extends React.Component { Array.from(Object.keys(Doc.GetProto(this.props.docViews[0].props.Document))). filter(key => key.startsWith("layout_")). map(key => runInAction(() => this._addedKeys.add(key.replace("layout_", "")))); - DocListCast(Cast(CurrentUserUtils.UserDocument.expandingButtons, Doc, null)?.data)?.map(btnDoc => { - if (StrCast(Cast(btnDoc?.dragFactory, Doc, null)?.title)) { - runInAction(() => this._addedKeys.add(StrCast(Cast(btnDoc?.dragFactory, Doc, null)?.title))); - } - }); } + return100 = () => 100; + @computed get scriptField() { + return ScriptField.MakeScript("switchView(firstDoc, this)", { this: Doc.name, heading: "string", checked: "string", containingTreeView: Doc.name, firstDoc: Doc.name }, + { firstDoc: this.props.docViews[0].props.Document }); + } render() { - const layout = Doc.Layout(this.props.docViews[0].Document); + const firstDoc = this.props.docViews[0].props.Document; + const templateName = StrCast(firstDoc.layoutKey, "layout").replace("layout_", ""); + const noteTypesDoc = Cast(Doc.UserDoc().noteTypes, Doc, null); + const noteTypes = DocListCast(noteTypesDoc?.data); + const addedTypes = DocListCast(Cast(Doc.UserDoc().templateButtons, Doc, null)?.data) + const layout = Doc.Layout(firstDoc); const templateMenu: Array = []; this.props.templates.forEach((checked, template) => templateMenu.push()); - templateMenu.push(); - templateMenu.push(); + templateMenu.push(); + templateMenu.push(); templateMenu.push(); - this._addedKeys && Array.from(this._addedKeys).map(layout => - templateMenu.push( this.toggleLayout(e, layout)} />) - ); + templateMenu.push(); + if (noteTypesDoc) { + addedTypes.concat(noteTypes).map(template => template.treeViewChecked = ComputedField.MakeFunction("templateIsUsed(this, firstDoc)", { firstDoc: "string" }, { firstDoc: StrCast(firstDoc.title) })); + this._addedKeys && Array.from(this._addedKeys).filter(key => !noteTypes.some(nt => nt.title === key)).forEach(template => templateMenu.push( + this.toggleLayout(e, template)} />)); + templateMenu.push( + false} + removeDocument={(doc: Doc) => false} + addDocument={(doc: Doc) => false} /> + ); + } return
      - {templateMenu} + {templateMenu}
    ; } -} \ No newline at end of file +} + +Scripting.addGlobal(function switchView(doc: Doc, template: Doc) { + if (template.dragFactory) { + template = Cast(template.dragFactory, Doc, null); + } + let templateTitle = StrCast(template?.title); + return templateTitle && DocumentView.makeCustomViewClicked(doc, undefined, Docs.Create.FreeformDocument, templateTitle, template) +}); + +Scripting.addGlobal(function templateIsUsed(templateDoc: Doc, firstDocTitlte: string) { + const firstDoc = SelectionManager.SelectedDocuments()[0].props.Document; + const template = StrCast(templateDoc.dragFactory ? Cast(templateDoc.dragFactory, Doc, null)?.title : templateDoc.title); + return StrCast(firstDoc.layoutKey) === "layout_" + template ? 'check' : 'unchecked'; + // return SelectionManager.SelectedDocuments().some(view => StrCast(view.props.Document.layoutKey) === "layout_" + template) ? 'check' : 'unchecked' +}) \ No newline at end of file diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 00e22d6fb..1fb78f625 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -2,7 +2,7 @@ import { library } from '@fortawesome/fontawesome-svg-core'; import { faFile } from '@fortawesome/free-solid-svg-icons'; import 'golden-layout/src/css/goldenlayout-base.css'; import 'golden-layout/src/css/goldenlayout-dark-theme.css'; -import { action, computed, Lambda, observable, reaction, runInAction } from "mobx"; +import { action, computed, Lambda, observable, reaction, runInAction, trace } from "mobx"; import { observer } from "mobx-react"; import * as ReactDOM from 'react-dom'; import Measure from "react-measure"; @@ -20,7 +20,7 @@ import { DocServer } from "../../DocServer"; import { Docs } from '../../documents/Documents'; import { DocumentType } from '../../documents/DocumentTypes'; import { DocumentManager } from '../../util/DocumentManager'; -import { DragManager } from "../../util/DragManager"; +import { DragManager, dropActionType } from "../../util/DragManager"; import { Scripting } from '../../util/Scripting'; import { SelectionManager } from '../../util/SelectionManager'; import { Transform } from '../../util/Transform'; @@ -504,15 +504,25 @@ export class CollectionDockingView extends React.Component { + const onDown = (e: React.PointerEvent) => { + if (!(e.nativeEvent as any).defaultPrevented) { e.preventDefault(); e.stopPropagation(); const dragData = new DragManager.DocumentDragData([doc]); - dragData.dropAction = doc.dropAction === "alias" ? "alias" : doc.dropAction === "copy" ? "copy" : undefined; + dragData.dropAction = doc.dropAction as dropActionType; DragManager.StartDocumentDrag([gearSpan], dragData, e.clientX, e.clientY); - }}>, gearSpan); + } + } + let rendered = false; + tab.buttonDisposer = reaction(() => ((view: Opt) => view ? [view] : [])(DocumentManager.Instance.getDocumentView(doc)), + (views) => { + !rendered && ReactDOM.render( + + , + gearSpan); + rendered = true; + }); + tab.reactComponents = [gearSpan]; tab.element.append(gearSpan); tab.reactionDisposer = reaction(() => ({ title: doc.title, degree: Doc.IsBrushedDegree(doc) }), ({ title, degree }) => { @@ -526,7 +536,8 @@ export class CollectionDockingView extends React.Component this.isCurrent(pair.layout)).map((pair, ind) => { + this.childLayoutPairs.map((pair, ind) => { Cast(pair.layout.proto?.onPointerUp, ScriptField)?.script.run({ this: pair.layout.proto }, console.log); }); } @@ -48,7 +48,7 @@ export class CollectionLinearView extends CollectionSubView(LinearDocument) { (i) => runInAction(() => { this._selectedIndex = i; let selected: any = undefined; - this.childLayoutPairs.filter((pair) => this.isCurrent(pair.layout)).map(async (pair, ind) => { + this.childLayoutPairs.map(async (pair, ind) => { const isSelected = this._selectedIndex === ind; if (isSelected) { selected = pair; @@ -71,8 +71,6 @@ export class CollectionLinearView extends CollectionSubView(LinearDocument) { } } - public isCurrent(doc: Doc) { return (Math.abs(NumCast(doc.displayTimecode, -1) - NumCast(this.Document.currentTimecode, -1)) < 1.5 || NumCast(doc.displayTimecode, -1) === -1); } - dimension = () => NumCast(this.props.Document._height); // 2 * the padding getTransform = (ele: React.RefObject) => () => { if (!ele.current) return Transform.Identity(); @@ -87,17 +85,21 @@ export class CollectionLinearView extends CollectionSubView(LinearDocument) {
    this.props.Document.linearViewIsExpanded = this.addMenuToggle.current!.checked)} /> - + -
    - {this.childLayoutPairs.filter((pair) => this.isCurrent(pair.layout)).map((pair, ind) => { +
    + {this.childLayoutPairs.map((pair, ind) => { const nested = pair.layout._viewType === CollectionViewType.Linear; const dref = React.createRef(); const nativeWidth = NumCast(pair.layout._nativeWidth, this.dimension()); const deltaSize = nativeWidth * .15 / 2; - return
    this._mainEle && this._mainEle.scrollHeight > this._mainEle.clientHeight && e.stopPropagation()} onDrop={this.onTreeDrop} diff --git a/src/client/views/collections/ParentDocumentSelector.tsx b/src/client/views/collections/ParentDocumentSelector.tsx index 43ba5c614..35e3a8958 100644 --- a/src/client/views/collections/ParentDocumentSelector.tsx +++ b/src/client/views/collections/ParentDocumentSelector.tsx @@ -2,7 +2,7 @@ import * as React from "react"; import './ParentDocumentSelector.scss'; import { Doc } from "../../../new_fields/Doc"; import { observer } from "mobx-react"; -import { observable, action, runInAction } from "mobx"; +import { observable, action, runInAction, trace, computed } from "mobx"; import { Id } from "../../../new_fields/FieldSymbols"; import { SearchUtil } from "../../util/SearchUtil"; import { CollectionDockingView } from "./CollectionDockingView"; @@ -14,6 +14,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faCog, faChevronCircleUp } from "@fortawesome/free-solid-svg-icons"; import { library } from "@fortawesome/fontawesome-svg-core"; import { DocumentView } from "../nodes/DocumentView"; +import { SelectionManager } from "../../util/SelectionManager"; const higflyout = require("@hig/flyout"); export const { anchorPoints } = higflyout; export const Flyout = higflyout.default; @@ -22,7 +23,6 @@ library.add(faCog); type SelectorProps = { Document: Doc, - Views: DocumentView[], Stack?: any, addDocTab(doc: Doc, location: string): void }; @@ -93,7 +93,7 @@ export class ParentDocSelector extends React.Component { } @observer -export class DockingViewButtonSelector extends React.Component<{ Document: Doc, Stack: any }> { +export class DockingViewButtonSelector extends React.Component<{ views: DocumentView[], Stack: any }> { @observable hover = false; customStylesheet(styles: any) { @@ -106,15 +106,19 @@ export class DockingViewButtonSelector extends React.Component<{ Document: Doc, }; } - render() { - const view = DocumentManager.Instance.getDocumentView(this.props.Document); - const flyout = ( + @computed get flyout() { + trace(); + return (
    - +
    ); - return !this.props.Stack && e.stopPropagation()} className="buttonSelector"> - + } + + render() { + trace(); + return { this.props.views[0].select(false); e.stopPropagation(); }} className="buttonSelector"> + ; diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx index 4bf3329eb..17bba9568 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -107,8 +107,14 @@ export class MarqueeView extends React.Component(Docu static makeCustomViewClicked = (doc: Doc, dataDoc: Opt, creator: (documents: Array, options: DocumentOptions, id?: string) => Doc, name: string = "custom", docLayoutTemplate?: Doc) => { const batch = UndoManager.StartBatch("CustomViewClicked"); const customName = "layout_" + name; - if (!StrCast(doc.title).endsWith(name)) doc.title = doc.title + "_" + name; if (doc[customName] === undefined) { const _width = NumCast(doc._width); const _height = NumCast(doc._height); @@ -634,13 +633,15 @@ export class DocumentView extends DocComponent(Docu // } else if (custom) { DocumentView.makeNativeViewClicked(this.props.Document); + const userDoc = Doc.UserDoc(); - const imgView = Cast(Doc.UserDoc().iconView, Doc, null); - const iconImgView = Cast(Doc.UserDoc().iconImageView, Doc, null); - const iconColView = Cast(Doc.UserDoc().iconColView, Doc, null); + const imgView = Cast(userDoc.iconView, Doc, null); + const iconImgView = Cast(userDoc.iconImageView, Doc, null); + const iconColView = Cast(userDoc.iconColView, Doc, null); const iconViews = [imgView, iconImgView, iconColView]; - const expandingButtons = DocListCast(Cast(Doc.UserDoc().expandingButtons, Doc, null)?.data); - const allTemplates = iconViews.concat(expandingButtons); + const templateButtons = DocListCast(Cast(userDoc.templateButtons, Doc, null)?.data); + const noteTypes = DocListCast(Cast(userDoc.noteTypes, Doc, null)?.data); + const allTemplates = iconViews.concat(templateButtons).concat(noteTypes); let foundLayout: Opt; allTemplates.map(btnDoc => (btnDoc.dragFactory as Doc) || btnDoc).filter(doc => doc.isTemplateDoc).forEach(tempDoc => { if (StrCast(tempDoc.title) === this.props.Document.type + "_" + layout) { @@ -1028,7 +1029,7 @@ export class DocumentView extends DocComponent(Docu
    ); const captionView = (!showCaption ? (null) :
    - { this.ProseRef = ele; - this.dropDisposer && this.dropDisposer(); + this.dropDisposer?.(); ele && (this.dropDisposer = DragManager.MakeDropTarget(ele, this.drop.bind(this))); } @@ -386,9 +387,14 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & } specificContextMenu = (e: React.MouseEvent): void => { const funcs: ContextMenuProps[] = []; - this.props.Document.isTemplateDoc && funcs.push({ description: "Make Default Layout", event: async () => Doc.UserDoc().defaultTextLayout = new PrefetchProxy(this.props.Document.proto as Doc), icon: "eye" }); + this.props.Document.isTemplateDoc && funcs.push({ description: "Make Default Layout", event: async () => Doc.UserDoc().defaultTextLayout = new PrefetchProxy(this.props.Document), icon: "eye" }); funcs.push({ description: "Reset Default Layout", event: () => Doc.UserDoc().defaultTextLayout = undefined, icon: "eye" }); - !this.props.Document.expandedTemplate && funcs.push({ description: "Make Template", event: () => { this.props.Document.isTemplateDoc = true; Doc.AddDocToList(Cast(Doc.UserDoc().noteTypes, Doc, null), "data", this.props.Document); }, icon: "eye" }); + !this.props.Document.expandedTemplate && funcs.push({ + description: "Make Template", event: () => { + this.props.Document.isTemplateDoc = makeTemplate(this.props.Document, true); + Doc.AddDocToList(Cast(Doc.UserDoc().noteTypes, Doc, null), "data", this.props.Document); + }, icon: "eye" + }); funcs.push({ description: "Toggle Single Line", event: () => this.props.Document._singleLine = !this.props.Document._singleLine, icon: "expand-arrows-alt" }); funcs.push({ description: "Toggle Sidebar", event: () => this.props.Document._showSidebar = !this.props.Document._showSidebar, icon: "expand-arrows-alt" }); funcs.push({ description: "Toggle Audio", event: () => this.props.Document._showAudio = !this.props.Document._showAudio, icon: "expand-arrows-alt" }); @@ -901,6 +907,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & if (e.buttons === 1 && this.props.isSelected(true) && !e.altKey) { e.stopPropagation(); } + this._downX = this._downY = Number.NaN; } @action @@ -914,12 +921,16 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & prosediv && (prosediv.keeplocation = undefined); const pos = this._editorView?.state.selection.$from.pos || 1; keeplocation && setTimeout(() => this._editorView?.dispatch(this._editorView?.state.tr.setSelection(TextSelection.create(this._editorView.state.doc, pos)))); + const coords = !Number.isNaN(this._downX) ? { left: this._downX, top: this._downY, bottom: this._downY, right: this._downX } : this._editorView?.coordsAtPos(pos); // jump rich text menu to this textbox - const { current } = this._ref; - if (current && this.props.Document._chromeStatus !== "disabled") { - const x = Math.min(Math.max(current.getBoundingClientRect().left, 0), window.innerWidth - RichTextMenu.Instance.width); - const y = this._ref.current!.getBoundingClientRect().top - RichTextMenu.Instance.height - 50; + const bounds = this._ref.current?.getBoundingClientRect(); + if (bounds && this.props.Document._chromeStatus !== "disabled") { + const x = Math.min(Math.max(bounds.left, 0), window.innerWidth - RichTextMenu.Instance.width); + let y = Math.min(Math.max(0, bounds.top - RichTextMenu.Instance.height - 50), window.innerHeight - RichTextMenu.Instance.height); + if (coords && coords.left > x && coords.left < x + RichTextMenu.Instance.width && coords.top > y && coords.top < y + RichTextMenu.Instance.height + 50) { + y = Math.min(bounds.bottom, window.innerHeight - RichTextMenu.Instance.height); + } RichTextMenu.Instance.jumpTo(x, y); } } diff --git a/src/client/views/search/SearchItem.tsx b/src/client/views/search/SearchItem.tsx index 2cbb24da7..63cef5101 100644 --- a/src/client/views/search/SearchItem.tsx +++ b/src/client/views/search/SearchItem.tsx @@ -272,7 +272,7 @@ export class SearchItem extends React.Component { @computed get contextButton() { - return CollectionDockingView.AddRightSplit(doc)} />; + return CollectionDockingView.AddRightSplit(doc)} />; } render() { diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index 50adf0392..322b57272 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -795,8 +795,6 @@ export namespace Doc { const prevLayout = StrCast(doc.layoutKey).split("_")[1]; const deiconify = prevLayout === "icon" && StrCast(doc.deiconifyLayout) ? "layout_" + StrCast(doc.deiconifyLayout) : ""; prevLayout === "icon" && (doc.deiconifyLayout = undefined); - if (StrCast(doc.title).endsWith("_" + prevLayout) && deiconify) doc.title = StrCast(doc.title).replace("_" + prevLayout, deiconify); - else doc.title = undefined; doc.layoutKey = deiconify || "layout"; } export function setDocFilterRange(target: Doc, key: string, range?: number[]) { diff --git a/src/new_fields/ScriptField.ts b/src/new_fields/ScriptField.ts index 9288fea9e..606f55b7c 100644 --- a/src/new_fields/ScriptField.ts +++ b/src/new_fields/ScriptField.ts @@ -119,8 +119,8 @@ export class ScriptField extends ObjectField { return compiled.compiled ? new ScriptField(compiled) : undefined; } - public static MakeScript(script: string, params: object = {}) { - const compiled = ScriptField.CompileScript(script, params, false); + public static MakeScript(script: string, params: object = {}, capturedVariables?: { [name: string]: Field }) { + const compiled = ScriptField.CompileScript(script, params, false, capturedVariables); return compiled.compiled ? new ScriptField(compiled) : undefined; } } diff --git a/src/new_fields/util.ts b/src/new_fields/util.ts index 6d7f6b56e..3ab1b299b 100644 --- a/src/new_fields/util.ts +++ b/src/new_fields/util.ts @@ -7,7 +7,6 @@ import { ObjectField } from "./ObjectField"; import { action, trace } from "mobx"; import { Parent, OnUpdate, Update, Id, SelfProxy, Self } from "./FieldSymbols"; import { DocServer } from "../client/DocServer"; -import { props } from "bluebird"; function _readOnlySetter(): never { throw new Error("Documents can't be modified in read-only mode"); diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 31588bf82..9c39ce7de 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -53,7 +53,7 @@ export class CurrentUserUtils { ]; doc.fieldTypes = Docs.Create.TreeDocument([], { title: "field enumerations" }); Doc.addFieldEnumerations(Doc.GetProto(noteTemplates[4]), "taskStatus", taskStatusValues); - doc.noteTypes = new PrefetchProxy(Docs.Create.TreeDocument(noteTemplates.map(nt => makeTemplate(nt, true, StrCast(nt.style)) ? nt : nt), { title: "Note Types", _height: 75 })); + doc.noteTypes = new PrefetchProxy(Docs.Create.TreeDocument(noteTemplates.map(nt => makeTemplate(nt, true, StrCast(nt.style)) ? nt : nt), { title: "Note Layouts", _height: 75 })); } // setup the "creator" buttons for the sidebar-- eg. the default set of draggable document creation tools @@ -292,12 +292,20 @@ export class CurrentUserUtils { { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: slideTemplate, removeDropProperties: new List(["dropAction"]), title: "presentation slide", icon: "sticky-note" }); doc.descriptionBtn = Docs.Create.FontIconDocument( { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: descriptionTemplate, removeDropProperties: new List(["dropAction"]), title: "description view", icon: "sticky-note" }); - doc.expandingButtons = Docs.Create.LinearDocument([doc.undoBtn as Doc, doc.redoBtn as Doc, doc.slidesBtn as Doc, doc.descriptionBtn as Doc, - ...DocListCast(Cast(doc.noteTypes, Doc, null))], { + doc.templateButtons = Docs.Create.LinearDocument([doc.slidesBtn as Doc, doc.descriptionBtn as Doc], { + title: "template buttons", _gridGap: 5, _xMargin: 5, _yMargin: 5, _height: 42, _width: 100, boxShadow: "0 0", dontSelect: true, + backgroundColor: "black", treeViewPreventOpen: true, forceActive: true, lockedPosition: true, _chromeStatus: "disabled", linearViewIsExpanded: true, + dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }) + }); + doc.expandingButtons = Docs.Create.LinearDocument([doc.undoBtn as Doc, doc.redoBtn as Doc, doc.templateButtons as Doc], { title: "expanding buttons", _gridGap: 5, _xMargin: 5, _yMargin: 5, _height: 42, _width: 100, boxShadow: "0 0", - backgroundColor: "black", treeViewPreventOpen: true, forceActive: true, lockedPosition: true, + backgroundColor: "black", treeViewPreventOpen: true, forceActive: true, lockedPosition: true, linearViewIsExpanded: true, dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }) }); + doc.templateDocs = new PrefetchProxy(Docs.Create.TreeDocument([doc.noteTypes as Doc, doc.templateButtons as Doc], { + title: "template layouts", _xPadding: 0, dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", + { dragData: DragManager.DocumentDragData.name }) + })); } // sets up the default set of documents to be shown in the Overlay layer -- cgit v1.2.3-70-g09d2 From aa8ed99f41a559a19ebea37b22ee1902aab2d6eb Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Fri, 27 Mar 2020 13:01:54 -0400 Subject: fixed iconifying doc script removal. fixed metadata to display inline-flex so that value truncates instead of moving to next line. --- src/client/util/RichTextSchema.tsx | 2 +- src/new_fields/Doc.ts | 13 +++++++------ src/server/authentication/models/current_user_utils.ts | 6 +++--- 3 files changed, 11 insertions(+), 10 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/util/RichTextSchema.tsx b/src/client/util/RichTextSchema.tsx index 31935df3e..659d317f6 100644 --- a/src/client/util/RichTextSchema.tsx +++ b/src/client/util/RichTextSchema.tsx @@ -875,7 +875,7 @@ export class DashFieldView { this._fieldWrapper.style.width = node.attrs.width; this._fieldWrapper.style.height = node.attrs.height; this._fieldWrapper.style.position = "relative"; - this._fieldWrapper.style.display = "inline-block"; + this._fieldWrapper.style.display = "inline-flex"; const self = this; this._enumerables = document.createElement("div"); diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index 322b57272..8447a4e93 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -587,7 +587,6 @@ export namespace Doc { target._nativeWidth = undefined; target._nativeHeight = undefined; target.type = undefined; - target.onClick = undefined; return; } @@ -598,8 +597,6 @@ export namespace Doc { titleTarget && (Doc.GetProto(target).title = titleTarget); Doc.GetProto(target)[targetKey] = new PrefetchProxy(templateDoc); } - const scriptField = ScriptCast(templateDoc.onClick); - scriptField && (target.onClick = scriptField[Copy]()); } target.layoutKey = targetKey; return target; @@ -791,6 +788,10 @@ export namespace Doc { return fieldStr === value; } + export function deiconifyView(doc: any) { + StrCast(doc.layoutKey).split("_")[1] === "icon" && setNativeView(doc); + } + export function setNativeView(doc: any) { const prevLayout = StrCast(doc.layoutKey).split("_")[1]; const deiconify = prevLayout === "icon" && StrCast(doc.deiconifyLayout) ? "layout_" + StrCast(doc.deiconifyLayout) : ""; @@ -813,8 +814,8 @@ export namespace Doc { } } - export function aliasDocs(field:any) { - return new List(field.map((d: any) => Doc.MakeAlias(d))); + export function aliasDocs(field: any) { + return new List(field.map((d: any) => Doc.MakeAlias(d))); } // filters document in a container collection: @@ -890,7 +891,7 @@ Scripting.addGlobal(function copyField(field: any) { return ObjectField.MakeCopy Scripting.addGlobal(function aliasDocs(field: any) { return Doc.aliasDocs(field); }); Scripting.addGlobal(function docList(field: any) { return DocListCast(field); }); Scripting.addGlobal(function sameDocs(doc1: any, doc2: any) { return Doc.AreProtosEqual(doc1, doc2); }); -Scripting.addGlobal(function setNativeView(doc: any) { Doc.setNativeView(doc); }); +Scripting.addGlobal(function deiconifyView(doc: any) { Doc.deiconifyView(doc); }); Scripting.addGlobal(function undo() { return UndoManager.Undo(); }); Scripting.addGlobal(function redo() { return UndoManager.Redo(); }); Scripting.addGlobal(function DOC(id: string) { console.log("Can't parse a document id in a script"); return "invalid"; }); diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 9c39ce7de..cfa13cb44 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -273,14 +273,14 @@ export class CurrentUserUtils { Doc.GetProto(descriptionTemplate).layout = FormattedTextBox.LayoutString("description"); descriptionTemplate.isTemplateDoc = makeTemplate(descriptionTemplate, true, "descriptionView"); - const iconDoc = Docs.Create.TextDocument("", { title: "icon", _width: 150, _height: 30, isTemplateDoc: true, onClick: ScriptField.MakeScript("setNativeView(this)") }); + const iconDoc = Docs.Create.TextDocument("", { title: "icon", _width: 150, _height: 30, isTemplateDoc: true, onClick: ScriptField.MakeScript("deiconifyView(this)") }); Doc.GetProto(iconDoc).icon = new RichTextField('{"doc":{"type":"doc","content":[{"type":"paragraph","attrs":{"align":null,"color":null,"id":null,"indent":null,"inset":null,"lineSpacing":null,"paddingBottom":null,"paddingTop":null},"content":[{"type":"dashField","attrs":{"fieldKey":"title","docid":""}}]}]},"selection":{"type":"text","anchor":2,"head":2},"storedMarks":[]}', ""); doc.isTemplateDoc = makeTemplate(iconDoc); doc.iconView = new PrefetchProxy(iconDoc); - const imgIconDoc = Docs.Create.ImageDocument("http://www.cs.brown.edu/~bcz/face.gif", { title: "data", _width: 50, isTemplateDoc: true, onClick: ScriptField.MakeScript("setNativeView(this)") }); + const imgIconDoc = Docs.Create.ImageDocument("http://www.cs.brown.edu/~bcz/face.gif", { title: "data", _width: 50, isTemplateDoc: true, onClick: ScriptField.MakeScript("deiconifyView(this)") }); doc.isTemplateDoc = makeTemplate(imgIconDoc, true, "image_icon"); doc.iconImageView = new PrefetchProxy(imgIconDoc); - const colIconDoc = Docs.Create.TreeDocument([], { title: "data", _width: 180, _height: 80, isTemplateDoc: true, onClick: ScriptField.MakeScript("setNativeView(this)") }); + const colIconDoc = Docs.Create.TreeDocument([], { title: "data", _width: 180, _height: 80, isTemplateDoc: true, onClick: ScriptField.MakeScript("deiconifyView(this)") }); doc.isTemplateDoc = makeTemplate(colIconDoc, true, "collection_icon"); doc.iconColView = new PrefetchProxy(colIconDoc); -- cgit v1.2.3-70-g09d2 From 4ae6b564896dd216c37fa38ffeee70ba0e671221 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Sat, 28 Mar 2020 02:40:17 -0400 Subject: simplified linkDocs to not keep a context -- instead, link are made between aliases which have a context. fixed clippings of PDFs to scroll correctly and resize in slideViews. fixed slideViews to render 'text' and 'data' instead of 'contents' and 'data' --- src/client/documents/Documents.ts | 6 ++---- src/client/util/DocumentManager.ts | 2 +- src/client/views/DocumentButtonBar.tsx | 2 -- src/client/views/collections/CollectionView.tsx | 4 +++- .../collections/collectionFreeForm/MarqueeView.tsx | 4 ++-- src/client/views/nodes/DocuLinkBox.tsx | 3 ++- src/client/views/nodes/DocumentView.tsx | 7 +++---- src/client/views/nodes/FormattedTextBox.tsx | 4 ++-- src/client/views/nodes/PDFBox.tsx | 2 +- src/client/views/nodes/PresBox.tsx | 2 +- src/client/views/pdf/PDFViewer.tsx | 18 +++++++++++------- src/server/authentication/models/current_user_utils.ts | 2 +- 12 files changed, 29 insertions(+), 27 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index b5cffaddd..dbea8062e 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -558,15 +558,13 @@ export namespace Docs { const linkDocProto = Doc.GetProto(doc); linkDocProto.anchor1 = source.doc; linkDocProto.anchor2 = target.doc; - linkDocProto.anchor1_context = source.ctx; - linkDocProto.anchor2_context = target.ctx; linkDocProto.anchor1_timecode = source.doc.currentTimecode || source.doc.displayTimecode; linkDocProto.anchor2_timecode = target.doc.currentTimecode || source.doc.displayTimecode; if (linkDocProto.layout_key1 === undefined) { Cast(linkDocProto.proto, Doc, null).layout_key1 = DocuLinkBox.LayoutString("anchor1"); Cast(linkDocProto.proto, Doc, null).layout_key2 = DocuLinkBox.LayoutString("anchor2"); - Cast(linkDocProto.proto, Doc, null).linkBoxExcludedKeys = new List(["treeViewExpandedView", "treeViewHideTitle", "removeDropProperties", "linkBoxExcludedKeys", "treeViewOpen", "proto", "aliasNumber", "isPrototype", "lastOpened", "creationDate", "author"]); + Cast(linkDocProto.proto, Doc, null).linkBoxExcludedKeys = new List(["treeViewExpandedView", "treeViewHideTitle", "removeDropProperties", "linkBoxExcludedKeys", "treeViewOpen", "aliasNumber", "isPrototype", "lastOpened", "creationDate", "author"]); Cast(linkDocProto.proto, Doc, null).layoutKey = undefined; } @@ -926,7 +924,7 @@ export namespace DocUtils { }); } - export function MakeLink(source: { doc: Doc, ctx?: Doc }, target: { doc: Doc, ctx?: Doc }, linkRelationship: string = "", id?: string) { + export function MakeLink(source: { doc: Doc }, target: { doc: Doc }, linkRelationship: string = "", id?: string) { const sv = DocumentManager.Instance.getDocumentView(source.doc); if (sv && sv.props.ContainingCollectionDoc === target.doc) return; if (target.doc === CurrentUserUtils.UserDocument) return undefined; diff --git a/src/client/util/DocumentManager.ts b/src/client/util/DocumentManager.ts index c41304b9f..0c410c4ce 100644 --- a/src/client/util/DocumentManager.ts +++ b/src/client/util/DocumentManager.ts @@ -203,7 +203,7 @@ export class DocumentManager { const second = secondDocWithoutView ? [secondDocWithoutView] : secondDocs; const linkDoc = first.length ? first[0] : second.length ? second[0] : undefined; const linkFollowDocs = first.length ? [await first[0].anchor2 as Doc, await first[0].anchor1 as Doc] : second.length ? [await second[0].anchor1 as Doc, await second[0].anchor2 as Doc] : undefined; - const linkFollowDocContexts = first.length ? [await first[0].anchor2_context as Doc, await first[0].anchor1_context as Doc] : second.length ? [await second[0].anchor1_context as Doc, await second[0].anchor2_context as Doc] : [undefined, undefined]; + const linkFollowDocContexts = first.length ? [await first[0].context as Doc, await first[0].context as Doc] : second.length ? [await second[0].context as Doc, await second[0].context as Doc] : [undefined, undefined]; const linkFollowTimecodes = first.length ? [NumCast(first[0].anchor2_timecode), NumCast(first[0].anchor1_timecode)] : second.length ? [NumCast(second[0].anchor1_timecode), NumCast(second[0].anchor2_timecode)] : [undefined, undefined]; if (linkFollowDocs && linkDoc) { const maxLocation = StrCast(linkDoc.maximizeLocation, "inTab"); diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx index 8a33232b4..ef1d20e44 100644 --- a/src/client/views/DocumentButtonBar.tsx +++ b/src/client/views/DocumentButtonBar.tsx @@ -120,8 +120,6 @@ export class DocumentButtonBar extends React.Component<{ views: (DocumentView | dragComplete: dropEv => { const linkDoc = dropEv.linkDragData?.linkDocument as Doc; // equivalent to !dropEve.aborted since linkDocument is only assigned on a completed drop if (this.view0 && linkDoc) { - const proto = Doc.GetProto(linkDoc); - proto.anchor1_context = this.view0.props.ContainingCollectionDoc; Doc.GetProto(linkDoc).linkRelationship = "hyperlink"; const anchor2Title = linkDoc.anchor2 instanceof Doc ? StrCast(linkDoc.anchor2.title) : "-untitled-"; diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index 2386f2d5d..1542988e7 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -127,6 +127,7 @@ export class CollectionView extends Touchable { const docList = DocListCast(targetDataDoc[this.props.fieldKey]); !docList.includes(doc) && (targetDataDoc[this.props.fieldKey] = new List([...docList, doc])); // DocAddToList may write to targetdataDoc's parent ... we don't want this. should really change GetProto to GetDataDoc and test for resolvedDataDoc there // Doc.AddDocToList(targetDataDoc, this.props.fieldKey, doc); + doc.context = this.props.Document; targetDataDoc[this.props.fieldKey + "-lastModified"] = new DateField(new Date(Date.now())); Doc.GetProto(doc).lastOpened = new DateField; return true; @@ -141,7 +142,8 @@ export class CollectionView extends Touchable { let index = value.reduce((p, v, i) => (v instanceof Doc && v === doc) ? i : p, -1); index = index !== -1 ? index : value.reduce((p, v, i) => (v instanceof Doc && Doc.AreProtosEqual(v, doc)) ? i : p, -1); - ContextMenu.Instance && ContextMenu.Instance.clearItems(); + doc.context = undefined; + ContextMenu.Instance?.clearItems(); if (index !== -1) { value.splice(index, 1); targetDataDoc[this.props.fieldKey] = new List(value); diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx index 17bba9568..0f94bffd6 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -111,7 +111,7 @@ export class MarqueeView extends React.Component(Doc if (!this._doubleTap) { this._editing = true; this.props.ContainingCollectionDoc && this.props.bringToFront(this.props.ContainingCollectionDoc, false); + const {clientX, clientY} = e; if (!this.props.Document.onClick && !this._isOpen) { this._timeout = setTimeout(action(() => { - if (Math.abs(e.clientX - this._downX) < 3 && Math.abs(e.clientY - this._downY) < 3 && (e.button !== 2 && !e.ctrlKey && this.props.Document.isButton)) { + if (Math.abs(clientX - this._downX) < 3 && Math.abs(clientY - this._downY) < 3 && (e.button !== 2 && !e.ctrlKey && this.props.Document.isButton)) { DocumentManager.Instance.FollowLink(this.props.Document, this.props.ContainingCollectionDoc as Doc, document => this.props.addDocTab(document, StrCast(this.props.Document.linkOpenLocation, "inTab")), false); } this._editing = false; diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 544c0a961..4968dd7fc 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -229,7 +229,6 @@ export class DocumentView extends DocComponent(Docu dragData.dropAction = dropAction; dragData.moveDocument = this.props.moveDocument;// this.Document.onDragStart ? undefined : this.props.moveDocument; dragData.dragDivName = this.props.dragDivName; - this.props.Document.anchor1_context = this.props.ContainingCollectionDoc; // bcz: !! shouldn't need this ... use search find the document's context dynamically DragManager.StartDocumentDrag([this._mainCont.current], dragData, x, y, { hideSource: !dropAction && !this.Document.onDragStart }); } } @@ -582,7 +581,7 @@ export class DocumentView extends DocComponent(Docu e.stopPropagation(); de.complete.annoDragData.linkedToDoc = true; - DocUtils.MakeLink({ doc: de.complete.annoDragData.annotationDocument }, { doc: this.props.Document, ctx: this.props.ContainingCollectionDoc }, "link"); + DocUtils.MakeLink({ doc: de.complete.annoDragData.annotationDocument }, { doc: this.props.Document }, "link"); } if (de.complete.docDragData) { if (de.complete.docDragData.applyAsTemplate) { @@ -613,7 +612,7 @@ export class DocumentView extends DocComponent(Docu // const views = docs.map(d => DocumentManager.Instance.getDocumentView(d)).filter(d => d).map(d => d as DocumentView); de.complete.linkDragData.linkSourceDocument !== this.props.Document && (de.complete.linkDragData.linkDocument = DocUtils.MakeLink({ doc: de.complete.linkDragData.linkSourceDocument }, - { doc: this.props.Document, ctx: this.props.ContainingCollectionDoc }, `link`)); // TODODO this is where in text links get passed + { doc: this.props.Document }, `link`)); // TODODO this is where in text links get passed } } @@ -639,7 +638,7 @@ export class DocumentView extends DocComponent(Docu const portalLink = DocListCast(this.Document.links).find(d => d.anchor1 === this.props.Document); if (!portalLink) { const portal = Docs.Create.FreeformDocument([], { _width: (this.layoutDoc._width || 0) + 10, _height: this.layoutDoc._height || 0, title: StrCast(this.props.Document.title) + ".portal" }); - DocUtils.MakeLink({ doc: this.props.Document, ctx: this.props.ContainingCollectionDoc }, { doc: portal }, "portal to"); + DocUtils.MakeLink({ doc: this.props.Document }, { doc: portal }, "portal to"); } this.Document.isButton = true; } diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index e7c9e5e6b..f83beade3 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -155,7 +155,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & this.dataDoc[key] = doc || Docs.Create.FreeformDocument([], { title: value, _width: 500, _height: 500 }, value); DocUtils.Publish(this.dataDoc[key] as Doc, value, this.props.addDocument, this.props.removeDocument); if (linkDoc) { (linkDoc as Doc).anchor2 = this.dataDoc[key] as Doc; } - else DocUtils.MakeLink({ doc: this.dataDoc, ctx: this.props.ContainingCollectionDoc }, { doc: this.dataDoc[key] as Doc }, "link to named target", id); + else DocUtils.MakeLink({ doc: this.props.Document }, { doc: this.dataDoc[key] as Doc }, "link to named target", id); }); }); }); @@ -748,7 +748,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & targetAnnotations?.push(pdfRegion); }); - const link = DocUtils.MakeLink({ doc: this.props.Document, ctx: this.props.ContainingCollectionDoc }, { doc: pdfRegion, ctx: pdfDoc }, "PDF pasted"); + const link = DocUtils.MakeLink({ doc: this.props.Document }, { doc: pdfRegion }, "PDF pasted"); if (link) { cbe.clipboardData!.setData("dash/linkDoc", link[Id]); const linkId = link[Id]; diff --git a/src/client/views/nodes/PDFBox.tsx b/src/client/views/nodes/PDFBox.tsx index 4076128b2..f8c008a2d 100644 --- a/src/client/views/nodes/PDFBox.tsx +++ b/src/client/views/nodes/PDFBox.tsx @@ -231,7 +231,7 @@ export class PDFBox extends DocAnnotatableComponent isChildActive = (outsideReaction?: boolean) => this._isChildActive; @computed get renderPdfView() { const pdfUrl = Cast(this.dataDoc[this.props.fieldKey], PdfField); - return
    + return
    { //docToJump stayed same meaning, it was not in the group or was the last element in the group const aliasOf = await Cast(docToJump.aliasOf, Doc); - const srcContext = aliasOf && await Cast(aliasOf.anchor1_context, Doc); + const srcContext = aliasOf && await Cast(aliasOf.context, Doc); if (docToJump === curDoc) { //checking if curDoc has navigation open const target = await Cast(curDoc.presentationTargetDoc, Doc); diff --git a/src/client/views/pdf/PDFViewer.tsx b/src/client/views/pdf/PDFViewer.tsx index af06a2646..a1e7d5c2a 100644 --- a/src/client/views/pdf/PDFViewer.tsx +++ b/src/client/views/pdf/PDFViewer.tsx @@ -7,7 +7,7 @@ import { Doc, DocListCast, FieldResult, WidthSym, Opt, HeightSym } from "../../. import { Id, Copy } from "../../../new_fields/FieldSymbols"; import { List } from "../../../new_fields/List"; import { makeInterface, createSchema } from "../../../new_fields/Schema"; -import { ScriptField } from "../../../new_fields/ScriptField"; +import { ScriptField, ComputedField } from "../../../new_fields/ScriptField"; import { Cast, NumCast, StrCast } from "../../../new_fields/Types"; import { smoothScroll, Utils, emptyFunction, returnOne, intersectRect, addStyleSheet, addStyleSheetRule, clearStyleSheetRules } from "../../../Utils"; import { Docs, DocUtils } from "../../documents/Documents"; @@ -33,6 +33,7 @@ import { TraceMobx } from "../../../new_fields/util"; import { PdfField } from "../../../new_fields/URLField"; import { PDFBox } from "../nodes/PDFBox"; import { FormattedTextBox } from "../nodes/FormattedTextBox"; +import { DocumentView } from "../nodes/DocumentView"; const PDFJSViewer = require("pdfjs-dist/web/pdf_viewer"); const pdfjsLib = require("pdfjs-dist"); @@ -210,7 +211,7 @@ export class PDFViewer extends DocAnnotatableComponent Cast(this.props.Document._scrollTop, "number", null), + this._scrollTopReactionDisposer = reaction(() => Cast(this.layoutDoc._scrollTop, "number", null), (stop) => (stop !== undefined) && this._mainCont.current && smoothScroll(500, this._mainCont.current, stop), { fireImmediately: true }); this._annotationReactionDisposer = reaction( () => DocListCast(this.dataDoc[this.props.fieldKey + "-annotations"]), @@ -567,12 +568,14 @@ export class PDFViewer extends DocAnnotatableComponent([clipDoc]); - Doc.GetProto(targetDoc).layout_slideView = (await Cast(Doc.UserDoc().slidesBtn, Doc))?.dragFactory; - targetDoc.layoutKey = "layout_slideView"; + DocumentView.makeCustomViewClicked(targetDoc, undefined, Docs.Create.StackingDocument, "slideView", undefined); // const targetDoc = Docs.Create.TextDocument("", { _width: 200, _height: 200, title: "Note linked to " + this.props.Document.title }); // Doc.GetProto(targetDoc).snipped = this.dataDoc[this.props.fieldKey][Copy](); // const snipLayout = Docs.Create.PdfDocument("http://www.msn.com", { title: "snippetView", isTemplateDoc: true, isTemplateForField: "snipped", _fitWidth: true, _width: this.marqueeWidth(), _height: this.marqueeHeight(), _scrollTop: this.marqueeY() }); @@ -582,7 +585,7 @@ export class PDFViewer extends DocAnnotatableComponent { if (!e.aborted && e.annoDragData && !e.annoDragData.linkedToDoc) { - const link = DocUtils.MakeLink({ doc: annotationDoc }, { doc: e.annoDragData.dropDocument, ctx: e.annoDragData.targetContext }, "Annotation"); + const link = DocUtils.MakeLink({ doc: annotationDoc }, { doc: e.annoDragData.dropDocument }, "Annotation"); if (link) link.maximizeLocation = "onRight"; } } @@ -646,6 +649,7 @@ export class PDFViewer extends DocAnnotatableComponent Date: Sat, 28 Mar 2020 10:56:01 -0400 Subject: fixed runtime errors when collection data field has image or non-list value. cleaned up creating buttons. --- src/client/views/collections/CollectionView.tsx | 2 +- src/new_fields/Doc.ts | 5 +- .../authentication/models/current_user_utils.ts | 81 +++++++++++----------- 3 files changed, 44 insertions(+), 44 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index 1542988e7..b01d76567 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -306,7 +306,7 @@ export class CollectionView extends Touchable { } get childDocs() { const dfield = this.dataField; - const rawdocs = (dfield instanceof Doc) ? [dfield] : Cast(dfield, listSpec(Doc), this.props.Document.expandedTemplate ? [Cast(this.props.Document.expandedTemplate, Doc, null)] : []); + const rawdocs = (dfield instanceof Doc) ? [dfield] : Cast(dfield, listSpec(Doc), Cast(this.props.Document.expandedTemplate, Doc, null) ? [Cast(this.props.Document.expandedTemplate, Doc, null)] : []); const docs = rawdocs.filter(d => !(d instanceof Promise)).map(d => d as Doc); const viewSpecScript = Cast(this.props.Document.viewSpecScript, ScriptField); return viewSpecScript ? docs.filter(d => viewSpecScript.script.run({ doc: d }, console.log).result) : docs; diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index da723b43b..9d90c569a 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -352,6 +352,9 @@ export namespace Doc { // return the doc's proto, but rather recursively searches through the proto inheritance chain // and returns the document who's proto is undefined or whose proto is marked as a base prototype ('isPrototype'). export function GetProto(doc: Doc): Doc { + if (doc instanceof Promise) { + console.log("GetProto: error: got Promise insead of Doc") + } const proto = doc && (Doc.GetT(doc, "isPrototype", "boolean", true) ? doc : (doc.proto || doc)); return proto === doc ? proto : Doc.GetProto(proto); } @@ -502,7 +505,7 @@ export namespace Doc { // if the childDoc is a template for a field, then this will return the expanded layout with its data doc. // otherwise, it just returns the childDoc export function GetLayoutDataDocPair(containerDoc: Doc, containerDataDoc: Opt, childDoc: Doc) { - if (!childDoc || !Doc.GetProto(childDoc)) { + if (!childDoc || childDoc instanceof Promise || !Doc.GetProto(childDoc)) { console.log("No, no, no!"); return { layout: childDoc, data: childDoc }; } diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index cb2b8846b..29fba38bc 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -1,7 +1,7 @@ import { action, computed, observable, reaction } from "mobx"; import * as rp from 'request-promise'; import { DocServer } from "../../../client/DocServer"; -import { Docs } from "../../../client/documents/Documents"; +import { Docs, DocumentOptions } from "../../../client/documents/Documents"; import { Attribute, AttributeGroup, Catalog, Schema } from "../../../client/northstar/model/idea/idea"; import { ArrayUtil } from "../../../client/northstar/utils/ArrayUtil"; import { UndoManager } from "../../../client/util/UndoManager"; @@ -81,7 +81,11 @@ export class CurrentUserUtils { { title: "use drag", icon: "mouse-pointer", click: 'deactivateInk();this.activePen.pen = this;', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "white", activePen: doc }, ]; return docProtoData.filter(d => !buttons || !buttons.includes(d.title)).map(data => Docs.Create.FontIconDocument({ - _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: data.click ? "copy" : undefined, title: data.title, icon: data.icon, ignoreClick: data.ignoreClick, + _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, + icon: data.icon, + title: data.title, + ignoreClick: data.ignoreClick, + dropAction: data.click ? "copy" : undefined, onDragStart: data.drag ? ScriptField.MakeFunction(data.drag) : undefined, onClick: data.click ? ScriptField.MakeScript(data.click) : undefined, ischecked: data.ischecked ? ComputedField.MakeFunction(data.ischecked) : undefined, activePen: data.activePen, dontSelect: true, backgroundColor: data.backgroundColor, removeDropProperties: new List(["dropAction"]), dragFactory: data.dragFactory, @@ -137,7 +141,8 @@ export class CurrentUserUtils { { title: "ignore gestures", icon: "signature", pointerUp: "setToolglass('none')", pointerDown: "setToolglass('ignoregesture')", backgroundColor: "green", ischecked: `sameDocs(this.activePen.pen, this)`, activePen: doc }, ]; return docProtoData.map(data => Docs.Create.FontIconDocument({ - _nativeWidth: 10, _nativeHeight: 10, _width: 10, _height: 10, dropAction: data.pointerDown ? "copy" : undefined, title: data.title, icon: data.icon, ignoreClick: data.ignoreClick, + _nativeWidth: 10, _nativeHeight: 10, _width: 10, _height: 10, title: data.title, icon: data.icon, + dropAction: data.pointerDown ? "copy" : undefined, ignoreClick: data.ignoreClick, onDragStart: data.drag ? ScriptField.MakeFunction(data.drag) : undefined, clipboard: data.clipboard, onPointerUp: data.pointerUp ? ScriptField.MakeScript(data.pointerUp) : undefined, onPointerDown: data.pointerDown ? ScriptField.MakeScript(data.pointerDown) : undefined, @@ -245,19 +250,20 @@ export class CurrentUserUtils { // setup the list of sidebar mode buttons which determine what is displayed in the sidebar static setupSidebarButtons(doc: Doc) { - doc.sidebarContainer = new Doc(); - (doc.sidebarContainer as Doc)._chromeStatus = "disabled"; - (doc.sidebarContainer as Doc).onClick = ScriptField.MakeScript("freezeSidebar()"); + const sidebarContainer = new Doc(); + doc.sidebarContainer = new PrefetchProxy(sidebarContainer); + sidebarContainer._chromeStatus = "disabled"; + sidebarContainer.onClick = ScriptField.MakeScript("freezeSidebar()"); - doc.ToolsBtn = this.setupToolsPanel(doc.sidebarContainer as Doc, doc); - doc.LibraryBtn = this.setupLibraryPanel(doc.sidebarContainer as Doc, doc); - doc.SearchBtn = this.setupSearchPanel(doc.sidebarContainer as Doc); + doc.ToolsBtn = new PrefetchProxy(this.setupToolsPanel(sidebarContainer, doc)); + doc.LibraryBtn = new PrefetchProxy(this.setupLibraryPanel(sidebarContainer, doc)); + doc.SearchBtn = new PrefetchProxy(this.setupSearchPanel(sidebarContainer)); // Finally, setup the list of buttons to display in the sidebar - doc.sidebarButtons = Docs.Create.StackingDocument([doc.SearchBtn as Doc, doc.LibraryBtn as Doc, doc.ToolsBtn as Doc], { + doc.sidebarButtons = new PrefetchProxy(Docs.Create.StackingDocument([doc.SearchBtn as any as Doc, doc.LibraryBtn as any as Doc, doc.ToolsBtn as any as Doc], { _width: 500, _height: 80, boxShadow: "0 0", _pivotField: "title", hideHeadings: true, ignoreClick: true, _chromeStatus: "view-mode", title: "sidebar btn row stack", backgroundColor: "dimGray", - }); + })); } /// sets up the default list of buttons to be shown in the expanding button menu at the bottom of the Dash window @@ -273,35 +279,26 @@ export class CurrentUserUtils { Doc.GetProto(descriptionTemplate).layout = FormattedTextBox.LayoutString("description"); descriptionTemplate.isTemplateDoc = makeTemplate(descriptionTemplate, true, "descriptionView"); - const iconDoc = Docs.Create.TextDocument("", { title: "icon", _width: 150, _height: 30, isTemplateDoc: true, onClick: ScriptField.MakeScript("deiconifyView(this)") }); - Doc.GetProto(iconDoc).icon = new RichTextField('{"doc":{"type":"doc","content":[{"type":"paragraph","attrs":{"align":null,"color":null,"id":null,"indent":null,"inset":null,"lineSpacing":null,"paddingBottom":null,"paddingTop":null},"content":[{"type":"dashField","attrs":{"fieldKey":"title","docid":""}}]}]},"selection":{"type":"text","anchor":2,"head":2},"storedMarks":[]}', ""); - doc.isTemplateDoc = makeTemplate(iconDoc); - doc.iconView = new PrefetchProxy(iconDoc); - const imgIconDoc = Docs.Create.ImageDocument("http://www.cs.brown.edu/~bcz/face.gif", { title: "data", _width: 50, isTemplateDoc: true, onClick: ScriptField.MakeScript("deiconifyView(this)") }); - doc.isTemplateDoc = makeTemplate(imgIconDoc, true, "image_icon"); - doc.iconImageView = new PrefetchProxy(imgIconDoc); - const colIconDoc = Docs.Create.TreeDocument([], { title: "data", _width: 180, _height: 80, isTemplateDoc: true, onClick: ScriptField.MakeScript("deiconifyView(this)") }); - doc.isTemplateDoc = makeTemplate(colIconDoc, true, "collection_icon"); - doc.iconColView = new PrefetchProxy(colIconDoc); - - doc.undoBtn = Docs.Create.FontIconDocument( - { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onClick: ScriptField.MakeScript("undo()"), removeDropProperties: new List(["dropAction"]), title: "undo button", icon: "undo-alt" }); - doc.redoBtn = Docs.Create.FontIconDocument( - { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onClick: ScriptField.MakeScript("redo()"), removeDropProperties: new List(["dropAction"]), title: "redo button", icon: "redo-alt" }); - doc.slidesBtn = Docs.Create.FontIconDocument( - { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: slideTemplate, removeDropProperties: new List(["dropAction"]), title: "presentation slide", icon: "sticky-note" }); - doc.descriptionBtn = Docs.Create.FontIconDocument( - { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: descriptionTemplate, removeDropProperties: new List(["dropAction"]), title: "description view", icon: "sticky-note" }); - doc.templateButtons = Docs.Create.LinearDocument([doc.slidesBtn as Doc, doc.descriptionBtn as Doc], { - title: "template buttons", _gridGap: 5, _xMargin: 5, _yMargin: 5, _height: 42, _width: 100, boxShadow: "0 0", dontSelect: true, - backgroundColor: "black", treeViewPreventOpen: true, forceActive: true, lockedPosition: true, _chromeStatus: "disabled", linearViewIsExpanded: true, - dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }) - }); - doc.expandingButtons = Docs.Create.LinearDocument([doc.undoBtn as Doc, doc.redoBtn as Doc, doc.templateButtons as Doc], { - title: "expanding buttons", _gridGap: 5, _xMargin: 5, _yMargin: 5, _height: 42, _width: 100, boxShadow: "0 0", - backgroundColor: "black", treeViewPreventOpen: true, forceActive: true, lockedPosition: true, linearViewIsExpanded: true, - dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }) - }); + doc.iconView = new PrefetchProxy(Docs.Create.TextDocument("", { title: "icon", _width: 150, _height: 30, isTemplateDoc: true, onClick: ScriptField.MakeScript("deiconifyView(this)") })); + Doc.GetProto(doc.iconView as any as Doc).icon = new RichTextField('{"doc":{"type":"doc","content":[{"type":"paragraph","attrs":{"align":null,"color":null,"id":null,"indent":null,"inset":null,"lineSpacing":null,"paddingBottom":null,"paddingTop":null},"content":[{"type":"dashField","attrs":{"fieldKey":"title","docid":""}}]}]},"selection":{"type":"text","anchor":2,"head":2},"storedMarks":[]}', ""); + doc.isTemplateDoc = makeTemplate(doc.iconView as any as Doc); + doc.ImageIconView = new PrefetchProxy(Docs.Create.ImageDocument("http://www.cs.brown.edu/~bcz/face.gif", { title: "data", _width: 50, isTemplateDoc: true, onClick: ScriptField.MakeScript("deiconifyView(this)") })); + doc.isTemplateDoc = makeTemplate(doc.ImageIconView as any as Doc, true, "image_icon"); + doc.iconColView = new PrefetchProxy(Docs.Create.TreeDocument([], { title: "data", _width: 180, _height: 80, isTemplateDoc: true, onClick: ScriptField.MakeScript("deiconifyView(this)") })); + doc.isTemplateDoc = makeTemplate(doc.iconColView as any as Doc, true, "collection_icon"); + + const ficon = (opts:DocumentOptions) => new PrefetchProxy(Docs.Create.FontIconDocument({...opts, dontSelect: true, dropAction: "alias", removeDropProperties: new List(["dropAction"]), _nativeWidth:100, _nativeHeight:100, _width:100, _height:100})) as any as Doc; + const blist = (opts:DocumentOptions, docs:Doc[]) => new PrefetchProxy(Docs.Create.LinearDocument(docs, {...opts, + _gridGap: 5, _xMargin: 5, _yMargin: 5, _height: 42, _width: 100, boxShadow: "0 0", dontSelect: true, + dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }), + backgroundColor: "black", treeViewPreventOpen: true, forceActive: true, lockedPosition: true, _chromeStatus: "disabled", linearViewIsExpanded: true})) as any as Doc; + + doc.undoBtn = ficon({ onClick: ScriptField.MakeScript("undo()"), title: "undo button", icon: "undo-alt" }); + doc.redoBtn = ficon({ onClick: ScriptField.MakeScript("redo()"), title: "redo button", icon: "redo-alt" }); + doc.slidesBtn = ficon({ onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: slideTemplate, removeDropProperties: new List(["dropAction"]), title: "presentation slide", icon: "sticky-note" }); + doc.descriptionBtn = ficon({ onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: descriptionTemplate, removeDropProperties: new List(["dropAction"]), title: "description view", icon: "sticky-note" }); + doc.templateButtons = blist({title: "template buttons"}, [doc.slidesBtn as Doc, doc.descriptionBtn as Doc]); + doc.expandingButtons = blist({ title: "expanding buttons"}, [doc.undoBtn as Doc, doc.redoBtn as Doc, doc.templateButtons as Doc]); doc.templateDocs = new PrefetchProxy(Docs.Create.TreeDocument([doc.noteTypes as Doc, doc.templateButtons as Doc], { title: "template layouts", _xPadding: 0, dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }) @@ -310,7 +307,7 @@ export class CurrentUserUtils { // sets up the default set of documents to be shown in the Overlay layer static setupOverlays(doc: Doc) { - doc.overlays = Docs.Create.FreeformDocument([], { title: "Overlays", backgroundColor: "#aca3a6" }); + doc.overlays = new PrefetchProxy(Docs.Create.FreeformDocument([], { title: "Overlays", backgroundColor: "#aca3a6" })); } // the initial presentation Doc to use @@ -320,7 +317,7 @@ export class CurrentUserUtils { } static setupMobileUploads(doc: Doc) { - doc.optionalRightCollection = Docs.Create.StackingDocument([], { title: "New mobile uploads" }); + doc.optionalRightCollection = new PrefetchProxy(Docs.Create.StackingDocument([], { title: "New mobile uploads" })); } static updateUserDocument(doc: Doc) { -- cgit v1.2.3-70-g09d2 From a639be6959f791ce34c148a9072cb9bd4faa5d6f Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Sat, 28 Mar 2020 11:57:40 -0400 Subject: from last --- src/client/util/RichTextRules.ts | 2 +- .../authentication/models/current_user_utils.ts | 22 ++++++++++++---------- 2 files changed, 13 insertions(+), 11 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/util/RichTextRules.ts b/src/client/util/RichTextRules.ts index 04a6fe21c..51a0aeb67 100644 --- a/src/client/util/RichTextRules.ts +++ b/src/client/util/RichTextRules.ts @@ -116,7 +116,7 @@ export class RichTextRules { }), // create an inline view of a document {{ : }} // {{:Doc}} => show default view of document {{}} => show layout for this doc {{ : Doc}} => show layout for another doc new InputRule( - new RegExp(/\{\{([a-zA-Z_ \-0-9]*)(\([a-zA-Z_ \-0-9]*\))(:[a-zA-Z_ \-0-9]+)?\}\}$/), + new RegExp(/\{\{([a-zA-Z_ \-0-9]*)(\([a-zA-Z_ \-0-9]*\))?(:[a-zA-Z_ \-0-9]+)?\}\}$/), (state, match, start, end) => { const fieldKey = match[1]; const fieldParam = match[2]; diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 29fba38bc..1c672e2d4 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -282,26 +282,28 @@ export class CurrentUserUtils { doc.iconView = new PrefetchProxy(Docs.Create.TextDocument("", { title: "icon", _width: 150, _height: 30, isTemplateDoc: true, onClick: ScriptField.MakeScript("deiconifyView(this)") })); Doc.GetProto(doc.iconView as any as Doc).icon = new RichTextField('{"doc":{"type":"doc","content":[{"type":"paragraph","attrs":{"align":null,"color":null,"id":null,"indent":null,"inset":null,"lineSpacing":null,"paddingBottom":null,"paddingTop":null},"content":[{"type":"dashField","attrs":{"fieldKey":"title","docid":""}}]}]},"selection":{"type":"text","anchor":2,"head":2},"storedMarks":[]}', ""); doc.isTemplateDoc = makeTemplate(doc.iconView as any as Doc); - doc.ImageIconView = new PrefetchProxy(Docs.Create.ImageDocument("http://www.cs.brown.edu/~bcz/face.gif", { title: "data", _width: 50, isTemplateDoc: true, onClick: ScriptField.MakeScript("deiconifyView(this)") })); - doc.isTemplateDoc = makeTemplate(doc.ImageIconView as any as Doc, true, "image_icon"); + doc.iconImageView = new PrefetchProxy(Docs.Create.ImageDocument("http://www.cs.brown.edu/~bcz/face.gif", { title: "data", _width: 50, isTemplateDoc: true, onClick: ScriptField.MakeScript("deiconifyView(this)") })); + doc.isTemplateDoc = makeTemplate(doc.iconImageView as any as Doc, true, "image_icon"); doc.iconColView = new PrefetchProxy(Docs.Create.TreeDocument([], { title: "data", _width: 180, _height: 80, isTemplateDoc: true, onClick: ScriptField.MakeScript("deiconifyView(this)") })); doc.isTemplateDoc = makeTemplate(doc.iconColView as any as Doc, true, "collection_icon"); - const ficon = (opts:DocumentOptions) => new PrefetchProxy(Docs.Create.FontIconDocument({...opts, dontSelect: true, dropAction: "alias", removeDropProperties: new List(["dropAction"]), _nativeWidth:100, _nativeHeight:100, _width:100, _height:100})) as any as Doc; - const blist = (opts:DocumentOptions, docs:Doc[]) => new PrefetchProxy(Docs.Create.LinearDocument(docs, {...opts, - _gridGap: 5, _xMargin: 5, _yMargin: 5, _height: 42, _width: 100, boxShadow: "0 0", dontSelect: true, + const ficon = (opts: DocumentOptions) => new PrefetchProxy(Docs.Create.FontIconDocument({ ...opts, dontSelect: true, dropAction: "alias", removeDropProperties: new List(["dropAction"]), _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100 })) as any as Doc; + const blist = (opts: DocumentOptions, docs: Doc[]) => new PrefetchProxy(Docs.Create.LinearDocument(docs, { + ...opts, + _gridGap: 5, _xMargin: 5, _yMargin: 5, _height: 42, _width: 100, boxShadow: "0 0", dontSelect: true, forceActive: true, dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }), - backgroundColor: "black", treeViewPreventOpen: true, forceActive: true, lockedPosition: true, _chromeStatus: "disabled", linearViewIsExpanded: true})) as any as Doc; + backgroundColor: "black", treeViewPreventOpen: true, lockedPosition: true, _chromeStatus: "disabled", linearViewIsExpanded: true + })) as any as Doc; doc.undoBtn = ficon({ onClick: ScriptField.MakeScript("undo()"), title: "undo button", icon: "undo-alt" }); doc.redoBtn = ficon({ onClick: ScriptField.MakeScript("redo()"), title: "redo button", icon: "redo-alt" }); doc.slidesBtn = ficon({ onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: slideTemplate, removeDropProperties: new List(["dropAction"]), title: "presentation slide", icon: "sticky-note" }); doc.descriptionBtn = ficon({ onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: descriptionTemplate, removeDropProperties: new List(["dropAction"]), title: "description view", icon: "sticky-note" }); - doc.templateButtons = blist({title: "template buttons"}, [doc.slidesBtn as Doc, doc.descriptionBtn as Doc]); - doc.expandingButtons = blist({ title: "expanding buttons"}, [doc.undoBtn as Doc, doc.redoBtn as Doc, doc.templateButtons as Doc]); + doc.templateButtons = blist({ title: "template buttons" }, [doc.slidesBtn as Doc, doc.descriptionBtn as Doc]); + doc.expandingButtons = blist({ title: "expanding buttons" }, [doc.undoBtn as Doc, doc.redoBtn as Doc, doc.templateButtons as Doc]); doc.templateDocs = new PrefetchProxy(Docs.Create.TreeDocument([doc.noteTypes as Doc, doc.templateButtons as Doc], { - title: "template layouts", _xPadding: 0, dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", - { dragData: DragManager.DocumentDragData.name }) + title: "template layouts", _xPadding: 0, + dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }) })); } -- cgit v1.2.3-70-g09d2 From 10f12b4fd55aea24421297dae31b4d32e2e274df Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Sat, 28 Mar 2020 13:11:15 -0400 Subject: fixed screenshot icon and tweaked checkbox --- src/client/views/DocumentButtonBar.tsx | 4 ++-- src/client/views/collections/CollectionTreeView.scss | 4 +++- src/client/views/collections/CollectionTreeView.tsx | 2 +- src/client/views/nodes/DocumentContentsView.tsx | 3 +-- src/server/authentication/models/current_user_utils.ts | 9 ++++----- 5 files changed, 11 insertions(+), 11 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx index ef1d20e44..e673189f9 100644 --- a/src/client/views/DocumentButtonBar.tsx +++ b/src/client/views/DocumentButtonBar.tsx @@ -1,5 +1,5 @@ import { IconProp, library } from '@fortawesome/fontawesome-svg-core'; -import { faArrowAltCircleDown, faArrowAltCircleUp, faCheckCircle, faCloudUploadAlt, faLink, faShare, faStopCircle, faSyncAlt, faTag, faTimes } from '@fortawesome/free-solid-svg-icons'; +import { faArrowAltCircleDown, faPhotoVideo, faArrowAltCircleUp, faCheckCircle, faCloudUploadAlt, faLink, faShare, faStopCircle, faSyncAlt, faTag, faTimes } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { action, computed, observable, runInAction } from "mobx"; import { observer } from "mobx-react"; @@ -25,7 +25,6 @@ import { DragManager } from '../util/DragManager'; import { MetadataEntryMenu } from './MetadataEntryMenu'; import { CurrentUserUtils } from '../../server/authentication/models/current_user_utils'; import GoogleAuthenticationManager from '../apis/GoogleAuthenticationManager'; -import { ComputedField } from '../../new_fields/ScriptField'; const higflyout = require("@hig/flyout"); export const { anchorPoints } = higflyout; export const Flyout = higflyout.default; @@ -40,6 +39,7 @@ library.add(faCheckCircle); library.add(faCloudUploadAlt); library.add(faSyncAlt); library.add(faShare); +library.add(faPhotoVideo) const cloud: IconProp = "cloud-upload-alt"; const fetch: IconProp = "sync-alt"; diff --git a/src/client/views/collections/CollectionTreeView.scss b/src/client/views/collections/CollectionTreeView.scss index 5efd97a6b..8e95f7fbe 100644 --- a/src/client/views/collections/CollectionTreeView.scss +++ b/src/client/views/collections/CollectionTreeView.scss @@ -35,7 +35,9 @@ width: 15px; color: $intermediate-color; margin-top: 3px; - transform: scale(1.3, 1.3); + transform: scale(1.3, 1.3); + border: #80808030 1px solid; + border-radius: 4px; } .editableView-container { diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index 53df7f041..387da8927 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -410,7 +410,7 @@ class TreeView extends React.Component { @computed get renderBullet() { const checked = this.props.document.type === DocumentType.COL ? undefined : this.props.onCheckedClick ? (this.props.document.treeViewChecked ? this.props.document.treeViewChecked : "unchecked") : undefined; - return
    + return
    {}
    ; } diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index a58115120..bf335937f 100644 --- a/src/client/views/nodes/DocumentContentsView.tsx +++ b/src/client/views/nodes/DocumentContentsView.tsx @@ -78,8 +78,7 @@ export class DocumentContentsView extends React.Component(), { title: "Presentation", _viewType: CollectionViewType.Stacking, _LODdisable: true, _chromeStatus: "replaced", _showTitle: "title", boxShadow: "0 0" }); const emptyCollection = Docs.Create.FreeformDocument([], { _nativeWidth: undefined, _nativeHeight: undefined, _LODdisable: true, _width: 150, _height: 100, title: "freeform" }); doc.activePen = doc; @@ -67,7 +67,7 @@ export class CurrentUserUtils { { title: "web page", icon: "globe-asia", ignoreClick: true, drag: 'Docs.Create.WebDocument("https://en.wikipedia.org/wiki/Hedgehog", {_width: 300, _height: 300, title: "New Webpage" })' }, { title: "cat image", icon: "cat", ignoreClick: true, drag: 'Docs.Create.ImageDocument("https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg", { _width: 200, title: "an image of a cat" })' }, { title: "buxton", icon: "cloud-upload-alt", ignoreClick: true, drag: "Docs.Create.Buxton()" }, - { title: "screenshot", icon: "frame", ignoreClick: true, drag: 'Docs.Create.ScreenshotDocument("", { _width: 400, _height: 200, title: "screen snapshot" })' }, + { title: "screenshot", icon: "photo-video", ignoreClick: true, drag: 'Docs.Create.ScreenshotDocument("", { _width: 400, _height: 200, title: "screen snapshot" })' }, { title: "webcam", icon: "video", ignoreClick: true, drag: 'Docs.Create.WebCamDocument("", { _width: 400, _height: 400, title: "a test cam" })' }, { title: "record", icon: "microphone", ignoreClick: true, drag: `Docs.Create.AudioDocument("${nullAudio}", { _width: 200, title: "ready to record audio" })` }, { title: "clickable button", icon: "bolt", ignoreClick: true, drag: 'Docs.Create.ButtonDocument({ _width: 150, _height: 50, title: "Button" })' }, @@ -80,7 +80,7 @@ export class CurrentUserUtils { { title: "use eraser", icon: "eraser", click: 'activateEraser(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "pink", activePen: doc }, { title: "use drag", icon: "mouse-pointer", click: 'deactivateInk();this.activePen.pen = this;', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "white", activePen: doc }, ]; - return docProtoData.filter(d => !buttons || !buttons.includes(d.title)).map(data => Docs.Create.FontIconDocument({ + return docProtoData.filter(d => !alreadyCreatedButtons?.includes(d.title)).map(data => Docs.Create.FontIconDocument({ _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, icon: data.icon, title: data.title, @@ -104,8 +104,7 @@ export class CurrentUserUtils { const dragdocs = await Cast(dragset.data, listSpec(Doc)); if (dragdocs) { const dragDocs = await Promise.all(dragdocs); - const newButtons = this.setupCreatorButtons(doc, dragDocs.map(d => StrCast(d.title))); - newButtons.map(nb => Doc.AddDocToList(dragset, "data", nb)); + this.setupCreatorButtons(doc, dragDocs.map(d => StrCast(d.title))).map(nb => Doc.AddDocToList(dragset, "data", nb)); } } } -- cgit v1.2.3-70-g09d2 From 6596e9aa8a23abe6f126e9cada5e3e8b8545884f Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 2 Apr 2020 12:42:44 -0400 Subject: cleaned up applying template code. fixed DocumentBox to work better with excluding collections + locking selection. --- .../apis/google_docs/GooglePhotosClientUtils.ts | 2 +- src/client/util/DragManager.ts | 1 - src/client/util/RichTextSchema.tsx | 2 +- src/client/views/TemplateMenu.tsx | 2 +- .../views/collections/CollectionTimeView.tsx | 2 +- src/client/views/nodes/DocumentBox.scss | 3 + src/client/views/nodes/DocumentBox.tsx | 19 +++- src/client/views/nodes/DocumentContentsView.tsx | 2 +- src/client/views/nodes/DocumentView.tsx | 118 ++++++++------------- src/client/views/pdf/PDFViewer.tsx | 2 +- src/new_fields/Doc.ts | 10 +- src/new_fields/RichTextUtils.ts | 4 +- src/new_fields/documentSchemas.ts | 3 +- .../authentication/models/current_user_utils.ts | 21 ++-- 14 files changed, 89 insertions(+), 102 deletions(-) (limited to 'src/server/authentication/models/current_user_utils.ts') diff --git a/src/client/apis/google_docs/GooglePhotosClientUtils.ts b/src/client/apis/google_docs/GooglePhotosClientUtils.ts index f8723f02d..7c4137f59 100644 --- a/src/client/apis/google_docs/GooglePhotosClientUtils.ts +++ b/src/client/apis/google_docs/GooglePhotosClientUtils.ts @@ -340,7 +340,7 @@ export namespace GooglePhotos { const url = data.url.href; const target = Doc.MakeAlias(source); const description = parseDescription(target, descriptionKey); - await DocumentView.makeCustomViewClicked(target, undefined, Docs.Create.FreeformDocument); + await DocumentView.makeCustomViewClicked(target, Docs.Create.FreeformDocument); media.push({ url, description }); } if (media.length) { diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index 8d3f6751e..db7a54ca8 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -137,7 +137,6 @@ export namespace DragManager { userDropAction: dropActionType; embedDoc?: boolean; moveDocument?: MoveFunction; - applyAsTemplate?: boolean; isSelectionMove?: boolean; // indicates that an explicitly selected Document is being dragged. this will suppress onDragStart scripts } export class LinkDragData { diff --git a/src/client/util/RichTextSchema.tsx b/src/client/util/RichTextSchema.tsx index 81ab95ff5..094cd58f3 100644 --- a/src/client/util/RichTextSchema.tsx +++ b/src/client/util/RichTextSchema.tsx @@ -776,7 +776,7 @@ export class DashDocView { if (dashDocBase instanceof Doc) { const aliasedDoc = Doc.MakeAlias(dashDocBase, docid + alias); aliasedDoc.layoutKey = "layout"; - node.attrs.fieldKey && DocumentView.makeCustomViewClicked(aliasedDoc, undefined, Docs.Create.StackingDocument, node.attrs.fieldKey, undefined); + node.attrs.fieldKey && DocumentView.makeCustomViewClicked(aliasedDoc, Docs.Create.StackingDocument, node.attrs.fieldKey, undefined); self.doRender(aliasedDoc, removeDoc, node, view, getPos); } }); diff --git a/src/client/views/TemplateMenu.tsx b/src/client/views/TemplateMenu.tsx index 996928cca..8eb5c5050 100644 --- a/src/client/views/TemplateMenu.tsx +++ b/src/client/views/TemplateMenu.tsx @@ -171,7 +171,7 @@ Scripting.addGlobal(function switchView(doc: Doc, template: Doc) { template = Cast(template.dragFactory, Doc, null); } const templateTitle = StrCast(template?.title); - return templateTitle && DocumentView.makeCustomViewClicked(doc, undefined, Docs.Create.FreeformDocument, templateTitle, template); + return templateTitle && DocumentView.makeCustomViewClicked(doc, Docs.Create.FreeformDocument, templateTitle, template); }); Scripting.addGlobal(function templateIsUsed(templateDoc: Doc, firstDocTitlte: string) { diff --git a/src/client/views/collections/CollectionTimeView.tsx b/src/client/views/collections/CollectionTimeView.tsx index 0d2207b27..4f77e8b0e 100644 --- a/src/client/views/collections/CollectionTimeView.tsx +++ b/src/client/views/collections/CollectionTimeView.tsx @@ -31,7 +31,7 @@ export class CollectionTimeView extends CollectionSubView(doc => doc) { componentDidMount() { this.props.Document._freezeOnDrop = true; const childDetailed = this.props.Document.childDetailed; // bcz: needs to be here to make sure the childDetailed layout template has been loaded when the first item is clicked; - const childText = "const alias = getAlias(this); Doc.ApplyTemplateTo(containingCollection.childDetailed, alias, 'layout_detailView'); alias.dropAction='alias'; alias.removeDropProperties=new List(['dropAction']); useRightSplit(alias, shiftKey); "; + const childText = "const alias = getAlias(this); Doc.ApplyTemplateTo(containingCollection.childDetailed, alias, 'layout_detailView'); alias.layoutKey='layout_detailedView'; alias.dropAction='alias'; alias.removeDropProperties=new List(['dropAction']); useRightSplit(alias, shiftKey); "; this.props.Document.onChildClick = ScriptField.MakeScript(childText, { this: Doc.name, heading: "string", containingCollection: Doc.name, shiftKey: "boolean" }); this.props.Document._fitToBox = true; if (!this.props.Document.onViewDefClick) { diff --git a/src/client/views/nodes/DocumentBox.scss b/src/client/views/nodes/DocumentBox.scss index 6fc87e4f1..ce21391ce 100644 --- a/src/client/views/nodes/DocumentBox.scss +++ b/src/client/views/nodes/DocumentBox.scss @@ -8,4 +8,7 @@ color: white; position: absolute; } + .contentFittingDocumentView { + position: absolute; + } } \ No newline at end of file diff --git a/src/client/views/nodes/DocumentBox.tsx b/src/client/views/nodes/DocumentBox.tsx index 9d1c08389..debe104d7 100644 --- a/src/client/views/nodes/DocumentBox.tsx +++ b/src/client/views/nodes/DocumentBox.tsx @@ -15,6 +15,8 @@ import "./DocumentBox.scss"; import { FieldView, FieldViewProps } from "./FieldView"; import React = require("react"); import { TraceMobx } from "../../../new_fields/util"; +import { DocumentView } from "./DocumentView"; +import { Docs } from "../../documents/Documents"; type DocBoxSchema = makeInterface<[typeof documentSchema]>; const DocBoxDocument = makeInterface(documentSchema); @@ -35,12 +37,12 @@ export class DocumentBox extends DocAnnotatableComponent { const funcs: ContextMenuProps[] = []; funcs.push({ description: (this.isSelectionLocked() ? "Show" : "Lock") + " Selection", event: () => this.toggleLockSelection, icon: "expand-arrows-alt" }); - funcs.push({ description: (this.props.Document.excludeCollections ? "Include" : "Exclude") + " Collections", event: () => this.props.Document.excludeCollections = !this.props.Document.excludeCollections, icon: "expand-arrows-alt" }); + funcs.push({ description: (this.props.Document.excludeCollections ? "Include" : "Exclude") + " Collections", event: () => Doc.GetProto(this.props.Document).excludeCollections = !this.props.Document.excludeCollections, icon: "expand-arrows-alt" }); funcs.push({ description: `${this.props.Document.forceActive ? "Select" : "Force"} Contents Active`, event: () => this.props.Document.forceActive = !this.props.Document.forceActive, icon: "project-diagram" }); ContextMenu.Instance.addItem({ description: "DocumentBox Funcs...", subitems: funcs, icon: "asterisk" }); @@ -105,14 +107,21 @@ export class DocumentBox extends DocAnnotatableComponent this.props.PanelHeight() - 2 * this.yPad; getTransform = () => this.props.ScreenToLocalTransform().translate(-this.xPad, -this.yPad); get renderContents() { - const containedDoc = this.contentDoc[this.props.fieldKey]; + const containedDoc = Cast(this.contentDoc[this.props.fieldKey], Doc, null); + const childTemplateName = StrCast(this.props.Document.childTemplateName); + if (containedDoc && childTemplateName && !containedDoc["layout_" + childTemplateName]) { + setTimeout(() => { + DocumentView.createCustomView(containedDoc, Docs.Create.StackingDocument, childTemplateName); + Doc.expandTemplateLayout(Cast(containedDoc["layout_" + childTemplateName], Doc, null)!, containedDoc, undefined); + }, 0); + } const contents = !(containedDoc instanceof Doc) ? (null) : + {this.renderContents}
    - {this.renderContents}
    ; } } diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index da035a6ce..68501fca2 100644 --- a/src/client/views/nodes/DocumentContentsView.tsx +++ b/src/client/views/nodes/DocumentContentsView.tsx @@ -59,7 +59,7 @@ export class DocumentContentsView extends React.Component Opt; }> { @computed get layout(): string { diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index d8bbd88ce..02a1ac527 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -508,58 +508,49 @@ export class DocumentView extends DocComponent(Docu @undoBatch deleteClicked = (): void => { SelectionManager.DeselectAll(); this.props.removeDocument?.(this.props.Document); } - static makeNativeViewClicked = (doc: Doc) => { - undoBatch(() => Doc.setNativeView(doc))(); - } - - static makeCustomViewClicked = (doc: Doc, dataDoc: Opt, creator: (documents: Array, options: DocumentOptions, id?: string) => Doc, templateSignature: string = "custom", docLayoutTemplate?: Doc) => { - const userDoc = Doc.UserDoc(); - const imgView = Cast(userDoc.iconView, Doc, null); - const iconImgView = Cast(userDoc.iconImageView, Doc, null); - const iconColView = Cast(userDoc.iconColView, Doc, null); - const iconViews = [imgView, iconImgView, iconColView]; - const templateButtons = DocListCast(Cast(userDoc.templateButtons, Doc, null)?.data); - const noteTypes = DocListCast(Cast(userDoc.noteTypes, Doc, null)?.data); - const allTemplates = iconViews.concat(templateButtons).concat(noteTypes); - const templateName = templateSignature.replace(/\(.*\)/, ""); - !docLayoutTemplate && allTemplates.map(btnDoc => (btnDoc.dragFactory as Doc) || btnDoc).filter(doc => doc.isTemplateDoc).forEach(tempDoc => { - if (StrCast(tempDoc.title) === doc.type + "_" + templateName) { - docLayoutTemplate = tempDoc; - } - }); - !docLayoutTemplate && allTemplates.map(btnDoc => (btnDoc.dragFactory as Doc) || btnDoc).filter(doc => doc.isTemplateDoc).forEach(tempDoc => { - if (StrCast(tempDoc.title) === templateName) { - docLayoutTemplate = tempDoc; + // applies a custom template to a document. the template is identified by it's short name (e.g, slideView not layout_slideView) + static makeCustomViewClicked = (doc: Doc, creator: (documents: Array, options: DocumentOptions, id?: string) => Doc, templateSignature: string = "custom", docLayoutTemplate?: Doc) => { + const batch = UndoManager.StartBatch("makeCustomViewClicked"); + runInAction(() => { + doc.layoutKey = "layout_" + templateSignature; + if (doc[doc.layoutKey] === undefined) { + DocumentView.createCustomView(doc, creator, templateSignature, docLayoutTemplate); } }); + batch.end(); + } + static createCustomView = (doc: Doc, creator: (documents: Array, options: DocumentOptions, id?: string) => Doc, templateSignature: string = "custom", docLayoutTemplate?: Doc) => { + const iconViews = DocListCast(Cast(Doc.UserDoc().iconViews, Doc, null)?.data); + const templBtns = DocListCast(Cast(Doc.UserDoc().templateButtons, Doc, null)?.data); + const noteTypes = DocListCast(Cast(Doc.UserDoc().noteTypes, Doc, null)?.data); + const allTemplates = iconViews.concat(templBtns).concat(noteTypes).map(btnDoc => (btnDoc.dragFactory as Doc) || btnDoc).filter(doc => doc.isTemplateDoc); + const templateName = templateSignature.replace(/\(.*\)/, ""); + // bcz: this is hacky -- want to have different templates be applied depending on the "type" of a document. but type is not reliable and there could be other types of template searches so this should be generalized + // first try to find a template that matches the specific document type (_). otherwise, fallback to a general match on + !docLayoutTemplate && allTemplates.forEach(tempDoc => StrCast(tempDoc.title) === doc.type + "_" + templateName && (docLayoutTemplate = tempDoc)); + !docLayoutTemplate && allTemplates.forEach(tempDoc => StrCast(tempDoc.title) === templateName && (docLayoutTemplate = tempDoc)); - const batch = UndoManager.StartBatch("CustomViewClicked"); const customName = "layout_" + templateSignature; - if (doc[customName] === undefined) { - const _width = NumCast(doc._width); - const _height = NumCast(doc._height); - const options = { title: "data", backgroundColor: StrCast(doc.backgroundColor), _autoHeight: true, _width, x: -_width / 2, y: - _height / 2, _showSidebar: false }; - - let fieldTemplate: Opt; - if (doc.data instanceof RichTextField || typeof (doc.data) === "string") { - fieldTemplate = Docs.Create.TextDocument("", options); - } else if (doc.data instanceof PdfField) { - fieldTemplate = Docs.Create.PdfDocument("http://www.msn.com", options); - } else if (doc.data instanceof VideoField) { - fieldTemplate = Docs.Create.VideoDocument("http://www.cs.brown.edu", options); - } else if (doc.data instanceof AudioField) { - fieldTemplate = Docs.Create.AudioDocument("http://www.cs.brown.edu", options); - } else if (doc.data instanceof ImageField) { - fieldTemplate = Docs.Create.ImageDocument("http://www.cs.brown.edu", options); - } - const docTemplate = docLayoutTemplate || creator(fieldTemplate ? [fieldTemplate] : [], { title: customName + "(" + doc.title + ")", isTemplateDoc: true, _width: _width + 20, _height: Math.max(100, _height + 45) }); - - fieldTemplate && Doc.MakeMetadataFieldTemplate(fieldTemplate, Doc.GetProto(docTemplate)); - Doc.ApplyTemplateTo(docTemplate, doc, customName, undefined); - } else { - doc.layoutKey = customName; + const _width = NumCast(doc._width); + const _height = NumCast(doc._height); + const options = { title: "data", backgroundColor: StrCast(doc.backgroundColor), _autoHeight: true, _width, x: -_width / 2, y: - _height / 2, _showSidebar: false }; + + let fieldTemplate: Opt; + if (doc.data instanceof RichTextField || typeof (doc.data) === "string") { + fieldTemplate = Docs.Create.TextDocument("", options); + } else if (doc.data instanceof PdfField) { + fieldTemplate = Docs.Create.PdfDocument("http://www.msn.com", options); + } else if (doc.data instanceof VideoField) { + fieldTemplate = Docs.Create.VideoDocument("http://www.cs.brown.edu", options); + } else if (doc.data instanceof AudioField) { + fieldTemplate = Docs.Create.AudioDocument("http://www.cs.brown.edu", options); + } else if (doc.data instanceof ImageField) { + fieldTemplate = Docs.Create.ImageDocument("http://www.cs.brown.edu", options); } - batch.end(); + const docTemplate = docLayoutTemplate || creator(fieldTemplate ? [fieldTemplate] : [], { title: customName + "(" + doc.title + ")", isTemplateDoc: true, _width: _width + 20, _height: Math.max(100, _height + 45) }); + + fieldTemplate && Doc.MakeMetadataFieldTemplate(fieldTemplate, Doc.GetProto(docTemplate)); + Doc.ApplyTemplateTo(docTemplate, doc, customName, undefined); } @undoBatch @@ -583,29 +574,6 @@ export class DocumentView extends DocComponent(Docu DocUtils.MakeLink({ doc: de.complete.annoDragData.annotationDocument }, { doc: this.props.Document }, "link"); } - if (de.complete.docDragData) { - if (de.complete.docDragData.applyAsTemplate) { - Doc.ApplyTemplateTo(de.complete.docDragData.draggedDocuments[0], this.props.Document, "layout_custom", undefined); - e.stopPropagation(); - } - else if (de.complete.docDragData.draggedDocuments[0].type === "text") { - const text = Cast(de.complete.docDragData.draggedDocuments[0].data, RichTextField)?.Text; - if (text && text[0] === "{" && text[text.length - 1] === "}" && text.includes(":")) { - const loc = text.indexOf(":"); - const key = text.slice(1, loc); - const value = text.slice(loc + 1, text.length - 1); - console.log(key); - console.log(value); - console.log(this.props.Document); - this.props.Document[key] = value; - console.log(de.complete.docDragData.draggedDocuments[0].x); - console.log(de.complete.docDragData.draggedDocuments[0].x); - e.preventDefault(); - e.stopPropagation(); - de.complete.aborted = true; - } - } - } if (de.complete.linkDragData) { e.stopPropagation(); // const docs = await SearchUtil.Search(`data_l:"${destDoc[Id]}"`, true); @@ -646,9 +614,9 @@ export class DocumentView extends DocComponent(Docu @undoBatch @action setCustomView = (custom: boolean, layout: string): void => { - DocumentView.makeNativeViewClicked(this.props.Document); + Doc.setNativeView(this.props.Document); if (custom) { - DocumentView.makeCustomViewClicked(this.props.Document, this.props.DataDoc, Docs.Create.StackingDocument, layout, undefined); + DocumentView.makeCustomViewClicked(this.props.Document, Docs.Create.StackingDocument, layout, undefined); } } @@ -1002,9 +970,9 @@ export class DocumentView extends DocComponent(Docu const ept = Doc.AreProtosEqual(this.props.Document, Cast(linkDoc.anchor1, Doc) as Doc) ? linkDoc.anchor1_timecode : linkDoc.anchor2_timecode; return anchor.type === DocumentType.AUDIO && NumCast(ept) ? false : true; } -c - @observable _link:Opt; - makeLink = () => { + + @observable _link: Opt; + makeLink = () => { return this._link; } diff --git a/src/client/views/pdf/PDFViewer.tsx b/src/client/views/pdf/PDFViewer.tsx index cc187cd67..71495d95f 100644 --- a/src/client/views/pdf/PDFViewer.tsx +++ b/src/client/views/pdf/PDFViewer.tsx @@ -575,7 +575,7 @@ export class PDFViewer extends DocAnnotatableComponent([clipDoc]); - DocumentView.makeCustomViewClicked(targetDoc, undefined, Docs.Create.StackingDocument, "slideView", undefined); + DocumentView.makeCustomViewClicked(targetDoc, Docs.Create.StackingDocument, "slideView", undefined); // const targetDoc = Docs.Create.TextDocument("", { _width: 200, _height: 200, title: "Note linked to " + this.props.Document.title }); // Doc.GetProto(targetDoc).snipped = this.dataDoc[this.props.fieldKey][Copy](); // const snipLayout = Docs.Create.PdfDocument("http://www.msn.com", { title: "snippetView", isTemplateDoc: true, isTemplateForField: "snipped", _fitWidth: true, _width: this.marqueeWidth(), _height: this.marqueeHeight(), _scrollTop: this.marqueeY() }); diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index 440f13d6b..a6cbabf42 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -592,7 +592,10 @@ export namespace Doc { let _applyCount: number = 0; export function ApplyTemplate(templateDoc: Doc) { if (templateDoc) { - const applied = ApplyTemplateTo(templateDoc, Doc.MakeDelegate(new Doc()), StrCast(templateDoc.layoutKey, "layout"), templateDoc.title + "(..." + _applyCount++ + ")"); + const target = Doc.MakeDelegate(new Doc()); + const targetKey = StrCast(templateDoc.layoutKey, "layout"); + const applied = ApplyTemplateTo(templateDoc, target, targetKey, templateDoc.title + "(..." + _applyCount++ + ")"); + target.layoutKey = targetKey; applied && (Doc.GetProto(applied).type = templateDoc.type); return applied; } @@ -615,7 +618,6 @@ export namespace Doc { Doc.GetProto(target)[targetKey] = new PrefetchProxy(templateDoc); } } - target.layoutKey = targetKey; return target; } @@ -920,7 +922,9 @@ Scripting.addGlobal(function curPresentationItem() { }); Scripting.addGlobal(function selectDoc(doc: any) { Doc.UserDoc().SelectedDocs = new List([doc]); }); Scripting.addGlobal(function selectedDocs(container: Doc, excludeCollections: boolean, prevValue: any) { - const docs = DocListCast(Doc.UserDoc().SelectedDocs).filter(d => !Doc.AreProtosEqual(d, container) && !d.annotationOn && d.type !== DocumentType.DOCUMENT && d.type !== DocumentType.KVP && (!excludeCollections || !Cast(d.data, listSpec(Doc), null))); + const docs = DocListCast(Doc.UserDoc().SelectedDocs). + filter(d => !Doc.AreProtosEqual(d, container) && !d.annotationOn && d.type !== DocumentType.DOCUMENT && d.type !== DocumentType.KVP && + (!excludeCollections || d.type !== DocumentType.COL || !Cast(d.data, listSpec(Doc), null))); return docs.length ? new List(docs) : prevValue; }); Scripting.addGlobal(function setDocFilter(container: Doc, key: string, value: any, modifiers?: "check" | "x" | undefined) { Doc.setDocFilter(container, key, value, modifiers); }); diff --git a/src/new_fields/RichTextUtils.ts b/src/new_fields/RichTextUtils.ts index 1d90c984d..c211b3d3c 100644 --- a/src/new_fields/RichTextUtils.ts +++ b/src/new_fields/RichTextUtils.ts @@ -274,7 +274,7 @@ export namespace RichTextUtils { const backingDocId = StrCast(textNote[guid]); if (!backingDocId) { const backingDoc = Docs.Create.ImageDocument(agnostic, { _width: 300, _height: 300 }); - DocumentView.makeCustomViewClicked(backingDoc, undefined, Docs.Create.FreeformDocument); + DocumentView.makeCustomViewClicked(backingDoc, Docs.Create.FreeformDocument); docid = backingDoc[Id]; textNote[guid] = docid; } else { @@ -403,7 +403,7 @@ export namespace RichTextUtils { let exported = (await Cast(linkDoc.anchor2, Doc))!; if (!exported.customLayout) { exported = Doc.MakeAlias(exported); - DocumentView.makeCustomViewClicked(exported, undefined, Docs.Create.FreeformDocument); + DocumentView.makeCustomViewClicked(exported, Docs.Create.FreeformDocument); linkDoc.anchor2 = exported; } url = Utils.shareUrl(exported[Id]); diff --git a/src/new_fields/documentSchemas.ts b/src/new_fields/documentSchemas.ts index e06452a4e..91ea32bee 100644 --- a/src/new_fields/documentSchemas.ts +++ b/src/new_fields/documentSchemas.ts @@ -61,7 +61,8 @@ export const documentSchema = createSchema({ fontSize: "string", fitToBox: "boolean", // whether freeform view contents should be zoomed/panned to fill the area of the document view letterSpacing: "string", - textTransform: "string" + textTransform: "string", + childTemplateName: "string" // the name of a template to use to override the layoutKey when rendering a document in DocumentBox }); export const positionSchema = createSchema({ diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index d9f354cf2..4f82da44d 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -55,6 +55,16 @@ export class CurrentUserUtils { Doc.addFieldEnumerations(Doc.GetProto(noteTemplates[4]), "taskStatus", taskStatusValues); doc.noteTypes = new PrefetchProxy(Docs.Create.TreeDocument(noteTemplates.map(nt => makeTemplate(nt, true, StrCast(nt.style)) ? nt : nt), { title: "Note Layouts", _height: 75 })); } + static setupDefaultIconTypes(doc: Doc, buttons?: string[]) { + doc.iconView = new PrefetchProxy(Docs.Create.TextDocument("", { title: "icon", _width: 150, _height: 30, isTemplateDoc: true, onClick: ScriptField.MakeScript("deiconifyView(this)") })); + Doc.GetProto(doc.iconView as any as Doc).icon = new RichTextField('{"doc":{"type":"doc","content":[{"type":"paragraph","attrs":{"align":null,"color":null,"id":null,"indent":null,"inset":null,"lineSpacing":null,"paddingBottom":null,"paddingTop":null},"content":[{"type":"dashField","attrs":{"fieldKey":"title","docid":""}}]}]},"selection":{"type":"text","anchor":2,"head":2},"storedMarks":[]}', ""); + doc.isTemplateDoc = makeTemplate(doc.iconView as any as Doc); + doc.iconImageView = new PrefetchProxy(Docs.Create.ImageDocument("http://www.cs.brown.edu/~bcz/face.gif", { title: "data", _width: 50, isTemplateDoc: true, onClick: ScriptField.MakeScript("deiconifyView(this)") })); + doc.isTemplateDoc = makeTemplate(doc.iconImageView as any as Doc, true, "image_icon"); + doc.iconColView = new PrefetchProxy(Docs.Create.TreeDocument([], { title: "data", _width: 180, _height: 80, isTemplateDoc: true, onClick: ScriptField.MakeScript("deiconifyView(this)") })); + doc.isTemplateDoc = makeTemplate(doc.iconColView as any as Doc, true, "collection_icon"); + doc.iconViews = Docs.Create.TreeDocument([doc.iconView as any as Doc, doc.iconImageView as any as Doc, doc.iconColView as any as Doc], { title: "icon types", _height: 75 }); + } // setup the "creator" buttons for the sidebar-- eg. the default set of draggable document creation tools static setupCreatorButtons(doc: Doc, alreadyCreatedButtons?: string[]) { @@ -63,7 +73,7 @@ export class CurrentUserUtils { doc.activePen = doc; const docProtoData: { title: string, icon: string, drag?: string, ignoreClick?: boolean, click?: string, ischecked?: string, activePen?: Doc, backgroundColor?: string, dragFactory?: Doc }[] = [ { title: "collection", icon: "folder", click: 'openOnRight(getCopy(this.dragFactory, true))', drag: 'getCopy(this.dragFactory, true)', dragFactory: emptyCollection }, - { title: "preview", icon: "expand", ignoreClick: true, drag: 'Docs.Create.DocumentDocument(ComputedField.MakeFunction("selectedDocs(this,true,[_last_])?.[0]"), { _width: 250, _height: 250, title: "container" })' }, + { title: "preview", icon: "expand", ignoreClick: true, drag: 'Docs.Create.DocumentDocument(ComputedField.MakeFunction("selectedDocs(this,this.excludeCollections,[_last_])?.[0]"), { _width: 250, _height: 250, title: "container" })' }, { title: "web page", icon: "globe-asia", ignoreClick: true, drag: 'Docs.Create.WebDocument("https://en.wikipedia.org/wiki/Hedgehog", {_width: 300, _height: 300, title: "New Webpage" })' }, { title: "cat image", icon: "cat", ignoreClick: true, drag: 'Docs.Create.ImageDocument("https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg", { _width: 200, title: "an image of a cat" })' }, { title: "buxton", icon: "cloud-upload-alt", ignoreClick: true, drag: "Docs.Create.Buxton()" }, @@ -278,14 +288,6 @@ export class CurrentUserUtils { Doc.GetProto(descriptionTemplate).layout = FormattedTextBox.LayoutString("description"); descriptionTemplate.isTemplateDoc = makeTemplate(descriptionTemplate, true, "descriptionView"); - doc.iconView = new PrefetchProxy(Docs.Create.TextDocument("", { title: "icon", _width: 150, _height: 30, isTemplateDoc: true, onClick: ScriptField.MakeScript("deiconifyView(this)") })); - Doc.GetProto(doc.iconView as any as Doc).icon = new RichTextField('{"doc":{"type":"doc","content":[{"type":"paragraph","attrs":{"align":null,"color":null,"id":null,"indent":null,"inset":null,"lineSpacing":null,"paddingBottom":null,"paddingTop":null},"content":[{"type":"dashField","attrs":{"fieldKey":"title","docid":""}}]}]},"selection":{"type":"text","anchor":2,"head":2},"storedMarks":[]}', ""); - doc.isTemplateDoc = makeTemplate(doc.iconView as any as Doc); - doc.iconImageView = new PrefetchProxy(Docs.Create.ImageDocument("http://www.cs.brown.edu/~bcz/face.gif", { title: "data", _width: 50, isTemplateDoc: true, onClick: ScriptField.MakeScript("deiconifyView(this)") })); - doc.isTemplateDoc = makeTemplate(doc.iconImageView as any as Doc, true, "image_icon"); - doc.iconColView = new PrefetchProxy(Docs.Create.TreeDocument([], { title: "data", _width: 180, _height: 80, isTemplateDoc: true, onClick: ScriptField.MakeScript("deiconifyView(this)") })); - doc.isTemplateDoc = makeTemplate(doc.iconColView as any as Doc, true, "collection_icon"); - const ficon = (opts: DocumentOptions) => new PrefetchProxy(Docs.Create.FontIconDocument({ ...opts, dontSelect: true, dropAction: "alias", removeDropProperties: new List(["dropAction"]), _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100 })) as any as Doc; const blist = (opts: DocumentOptions, docs: Doc[]) => new PrefetchProxy(Docs.Create.LinearDocument(docs, { ...opts, @@ -324,6 +326,7 @@ export class CurrentUserUtils { static updateUserDocument(doc: Doc) { doc.title = Doc.CurrentUserEmail; new InkingControl(); + (doc.iconTypes === undefined) && CurrentUserUtils.setupDefaultIconTypes(doc); (doc.noteTypes === undefined) && CurrentUserUtils.setupDefaultDocTemplates(doc); (doc.optionalRightCollection === undefined) && CurrentUserUtils.setupMobileUploads(doc); (doc.overlays === undefined) && CurrentUserUtils.setupOverlays(doc); -- cgit v1.2.3-70-g09d2