diff options
40 files changed, 1435 insertions, 491 deletions
diff --git a/.vscode/settings.json b/.vscode/settings.json index 0b45c3f46..e636c9d73 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -11,5 +11,9 @@ "typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets": false, "typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": true, "search.usePCRE2": true, - "typescript.tsdk": "node_modules/typescript/lib" + "typescript.tsdk": "node_modules/typescript/lib", + "python.testing.promptToConfigure": false, + "python.testing.pytestEnabled": false, + "python.testing.unittestEnabled": false, + "python.testing.nosetestsEnabled": false }
\ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 585c0aa1e..e692b266d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -963,6 +963,15 @@ "@types/react": "*" } }, + "@types/react-grid-layout": { + "version": "0.17.1", + "resolved": "https://registry.npmjs.org/@types/react-grid-layout/-/react-grid-layout-0.17.1.tgz", + "integrity": "sha512-1ssQjX3X2A89jx94jECJ0Ze2EHFRYlBHjRh2pnlwjJj1WaEijXUNvwKnUzKwgNFnyZ91Pzqu9Z3V7Atzi9ge7A==", + "dev": true, + "requires": { + "@types/react": "*" + } + }, "@types/react-measure": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/@types/react-measure/-/react-measure-2.0.6.tgz", @@ -3528,6 +3537,11 @@ "delayed-stream": "~1.0.0" } }, + "command-exists": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/command-exists/-/command-exists-1.2.6.tgz", + "integrity": "sha512-Qst/zUUNmS/z3WziPxyqjrcz09pm+2Knbs5mAZL4VAE0sSrNY1/w8+/YxeHcoBTsO6iojA6BW7eFf27Eg2MRuw==" + }, "command-line-usage": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-4.1.0.tgz", @@ -8022,6 +8036,11 @@ "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz", "integrity": "sha1-LRd/ZS+jHpObRDjVNBSZ36OCXpk=" }, + "lodash.isequal": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz", + "integrity": "sha1-QVxEePK8wwEgwizhDtMib30+GOA=" + }, "lodash.isplainobject": { "version": "4.0.6", "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", @@ -12944,6 +12963,11 @@ "os-tmpdir": "^1.0.0" } }, + "p-debounce": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-debounce/-/p-debounce-1.0.0.tgz", + "integrity": "sha1-y38svu/YegnrqGHhErZ1J+Yh4v0=" + }, "p-defer": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/p-defer/-/p-defer-1.0.0.tgz", @@ -14076,6 +14100,27 @@ "scheduler": "^0.19.1" } }, + "react-draggable": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/react-draggable/-/react-draggable-4.4.3.tgz", + "integrity": "sha512-jV4TE59MBuWm7gb6Ns3Q1mxX8Azffb7oTtDtBgFkxRvhDp38YAARmRplrj0+XGkhOJB5XziArX+4HUUABtyZ0w==", + "requires": { + "classnames": "^2.2.5", + "prop-types": "^15.6.0" + } + }, + "react-grid-layout": { + "version": "0.18.3", + "resolved": "https://registry.npmjs.org/react-grid-layout/-/react-grid-layout-0.18.3.tgz", + "integrity": "sha512-lHkrk941Tk5nTwZPa9uj6ttHBT0VehSHwEhWbINBJKvM1GRaFNOefvjcuxSyuCI5JWjVUP+Qm3ARt2470AlxMA==", + "requires": { + "classnames": "2.x", + "lodash.isequal": "^4.0.0", + "prop-types": "^15.0.0", + "react-draggable": "^4.0.0", + "react-resizable": "^1.9.0" + } + }, "react-image-lightbox-with-rotate": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/react-image-lightbox-with-rotate/-/react-image-lightbox-with-rotate-5.1.1.tgz", @@ -14144,6 +14189,15 @@ } } }, + "react-resizable": { + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/react-resizable/-/react-resizable-1.10.1.tgz", + "integrity": "sha512-Jd/bKOKx6+19NwC4/aMLRu/J9/krfxlDnElP41Oc+oLiUWs/zwV1S9yBfBZRnqAwQb6vQ/HRSk3bsSWGSgVbpw==", + "requires": { + "prop-types": "15.x", + "react-draggable": "^4.0.3" + } + }, "react-table": { "version": "6.11.5", "resolved": "https://registry.npmjs.org/react-table/-/react-table-6.11.5.tgz", @@ -15949,6 +16003,20 @@ "readable-stream": "^3.1.1" } }, + "temp-dir": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/temp-dir/-/temp-dir-1.0.0.tgz", + "integrity": "sha1-CnwOom06Oa+n4OvqnB/AvE2qAR0=" + }, + "tempy": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/tempy/-/tempy-0.2.1.tgz", + "integrity": "sha512-LB83o9bfZGrntdqPuRdanIVCPReam9SOZKW0fOy5I9X3A854GGWi0tjCqoXEk84XIEYBc/x9Hq3EFop/H5wJaw==", + "requires": { + "temp-dir": "^1.0.0", + "unique-string": "^1.0.0" + } + }, "term-size": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/term-size/-/term-size-1.2.0.tgz", @@ -16524,6 +16592,40 @@ "resolved": "https://registry.npmjs.org/typescript-collections/-/typescript-collections-1.3.3.tgz", "integrity": "sha512-7sI4e/bZijOzyURng88oOFZCISQPTHozfE2sUu5AviFYk5QV7fYGb6YiDl+vKjF/pICA354JImBImL9XJWUvdQ==" }, + "typescript-language-server": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/typescript-language-server/-/typescript-language-server-0.4.0.tgz", + "integrity": "sha512-K8jNOmDFn+QfrCh8ujby2pGDs5rpjYZQn+zvQnf42rxG4IHbfw5CHoMvbGkWPK/J5Gw8/l5K3i03kVZC2IBElg==", + "requires": { + "command-exists": "1.2.6", + "commander": "^2.11.0", + "fs-extra": "^7.0.0", + "p-debounce": "^1.0.0", + "tempy": "^0.2.1", + "vscode-languageserver": "^5.3.0-next", + "vscode-uri": "^1.0.5" + }, + "dependencies": { + "fs-extra": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-7.0.1.tgz", + "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==", + "requires": { + "graceful-fs": "^4.1.2", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" + } + }, + "jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", + "requires": { + "graceful-fs": "^4.1.6" + } + } + } + }, "typical": { "version": "2.6.1", "resolved": "https://registry.npmjs.org/typical/-/typical-2.6.1.tgz", @@ -16678,6 +16780,11 @@ "crypto-random-string": "^1.0.0" } }, + "universalify": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==" + }, "unpack-string": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/unpack-string/-/unpack-string-0.0.2.tgz", @@ -16920,6 +17027,44 @@ "resolved": "https://registry.npmjs.org/void-elements/-/void-elements-2.0.1.tgz", "integrity": "sha1-wGavtYK7HLQSjWDqkjkulNXp2+w=" }, + "vscode-jsonrpc": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-5.0.1.tgz", + "integrity": "sha512-JvONPptw3GAQGXlVV2utDcHx0BiY34FupW/kI6mZ5x06ER5DdPG/tXWMVHjTNULF5uKPOUUD0SaXg5QaubJL0A==" + }, + "vscode-languageserver": { + "version": "5.3.0-next.10", + "resolved": "https://registry.npmjs.org/vscode-languageserver/-/vscode-languageserver-5.3.0-next.10.tgz", + "integrity": "sha512-QL7Fe1FT6PdLtVzwJeZ78pTic4eZbzLRy7yAQgPb9xalqqgZESR0+yDZPwJrM3E7PzOmwHBceYcJR54eQZ7Kng==", + "requires": { + "vscode-languageserver-protocol": "^3.15.0-next.8", + "vscode-textbuffer": "^1.0.0" + } + }, + "vscode-languageserver-protocol": { + "version": "3.15.3", + "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.15.3.tgz", + "integrity": "sha512-zrMuwHOAQRhjDSnflWdJG+O2ztMWss8GqUUB8dXLR/FPenwkiBNkMIJJYfSN6sgskvsF0rHAoBowNQfbyZnnvw==", + "requires": { + "vscode-jsonrpc": "^5.0.1", + "vscode-languageserver-types": "3.15.1" + } + }, + "vscode-languageserver-types": { + "version": "3.15.1", + "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.15.1.tgz", + "integrity": "sha512-+a9MPUQrNGRrGU630OGbYVQ+11iOIovjCkqxajPa9w57Sd5ruK8WQNsslzpa0x/QJqC8kRc2DUxWjIFwoNm4ZQ==" + }, + "vscode-textbuffer": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/vscode-textbuffer/-/vscode-textbuffer-1.0.0.tgz", + "integrity": "sha512-zPaHo4urgpwsm+PrJWfNakolRpryNja18SUip/qIIsfhuEqEIPEXMxHOlFPjvDC4JgTaimkncNW7UMXRJTY6ow==" + }, + "vscode-uri": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-1.0.8.tgz", + "integrity": "sha512-obtSWTlbJ+a+TFRYGaUumtVwb+InIUVI0Lu0VBUAPmj2cU5JutEXg3xUE0c2J5Tcy7h2DEKVJBFi+Y9ZSFzzPQ==" + }, "vue-template-compiler": { "version": "2.6.11", "resolved": "https://registry.npmjs.org/vue-template-compiler/-/vue-template-compiler-2.6.11.tgz", diff --git a/package.json b/package.json index 20614f5eb..b9d77b923 100644 --- a/package.json +++ b/package.json @@ -69,6 +69,7 @@ "@types/react": "^16.9.19", "@types/react-autosuggest": "^9.3.13", "@types/react-color": "^2.17.3", + "@types/react-grid-layout": "^0.17.1", "@types/react-measure": "^2.0.6", "@types/react-table": "^6.8.6", "@types/request": "^2.48.4", @@ -206,9 +207,11 @@ "react-color": "^2.18.0", "react-compound-slider": "^2.5.0", "react-dom": "^16.12.0", + "react-grid-layout": "^0.18.3", "react-image-lightbox-with-rotate": "^5.1.1", "react-jsx-parser": "^1.21.0", "react-measure": "^2.2.4", + "react-resizable": "^1.10.1", "react-table": "^6.11.5", "readline": "^1.3.0", "request": "^2.88.0", @@ -222,6 +225,7 @@ "solr-node": "^1.2.1", "standard-http-error": "^2.0.1", "typescript-collections": "^1.3.3", + "typescript-language-server": "^0.4.0", "url-loader": "^1.1.2", "uuid": "^3.4.0", "valid-url": "^1.0.9", diff --git a/src/client/DocServer.ts b/src/client/DocServer.ts index c6b3fa61f..c7dfb0b23 100644 --- a/src/client/DocServer.ts +++ b/src/client/DocServer.ts @@ -1,6 +1,6 @@ import * as io from 'socket.io-client'; import { MessageStore, YoutubeQueryTypes, GestureContent, MobileInkOverlayContent, UpdateMobileInkOverlayPositionContent, MobileDocumentUploadContent } from "./../server/Message"; -import { Opt, Doc } from '../fields/Doc'; +import { Opt, Doc, fetchProto } from '../fields/Doc'; import { Utils, emptyFunction } from '../Utils'; import { SerializationHelper } from './util/SerializationHelper'; import { RefField } from '../fields/RefField'; @@ -244,7 +244,10 @@ export namespace DocServer { return cached; } else { // CACHED => great, let's just return the cached field we have - return Promise.resolve(cached); + return Promise.resolve(cached).then(field => { + (field instanceof Doc) && fetchProto(field); + return field; + }); } }; const _GetCachedRefFieldImpl = (id: string): Opt<RefField> => { diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 8d867348f..002bfe6a2 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -606,7 +606,6 @@ export namespace Docs { selection: { type: "text", anchor: 1, head: 1 }, storedMarks: [] }; - const field = text ? new RichTextField(JSON.stringify(rtf), text) : undefined; return InstanceFromProto(Prototypes.get(DocumentType.RTF), field, options, undefined, fieldKey); } @@ -696,7 +695,7 @@ export namespace Docs { } export function SchemaDocument(schemaColumns: SchemaHeaderField[], documents: Array<Doc>, options: DocumentOptions) { - return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", schemaColumns: new List(schemaColumns), ...options, _viewType: CollectionViewType.Schema }); + return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", schemaColumns: new List(schemaColumns.length ? schemaColumns : [new SchemaHeaderField("title", "#f1efeb")]), ...options, _viewType: CollectionViewType.Schema }); } export function TreeDocument(documents: Array<Doc>, options: DocumentOptions, id?: string) { @@ -823,7 +822,8 @@ export namespace DocUtils { if (sv && sv.props.ContainingCollectionDoc === target.doc) return; if (target.doc === Doc.UserDoc()) return undefined; - const linkDoc = Docs.Create.LinkDocument(source, target, { linkRelationship }, id); + const linkDoc = Docs.Create.LinkDocument(source, target, { linkRelationship, layoutKey: "layout_linkView" }, id); + linkDoc.layout_linkView = Cast(Cast(Doc.UserDoc()["template-button-link"], Doc, null).dragFactory, Doc, null); Doc.GetProto(linkDoc).title = ComputedField.MakeFunction('self.anchor1.title +" (" + (self.linkRelationship||"to") +") " + self.anchor2.title'); Doc.GetProto(source.doc).links = ComputedField.MakeFunction("links(self)"); diff --git a/src/client/util/CurrentUserUtils.ts b/src/client/util/CurrentUserUtils.ts index e1605473c..323e398be 100644 --- a/src/client/util/CurrentUserUtils.ts +++ b/src/client/util/CurrentUserUtils.ts @@ -87,6 +87,52 @@ export class CurrentUserUtils { }); } + if (doc["template-button-link"] === undefined) { + const linkTemplate = Docs.Create.TextDocument(" ", { title: "header", _height: 100 }, "header"); // text needs to be a space to allow templateText to be created + Doc.GetProto(linkTemplate).layout = + "<div>" + + " <FormattedTextBox {...props} height='{this._headerHeight||75}px' background='{this._headerColor||`lightBlue`}' fieldKey={'header'}/>" + + " <FormattedTextBox {...props} position='absolute' top='{(this._headerHeight||75)*scale}px' height='calc({100/scale}% - {this._headerHeight||75}px)' fieldKey={'text'}/>" + + "</div>"; + linkTemplate.isTemplateDoc = makeTemplate(linkTemplate, true, "linkView"); + + const rtf2 = { + doc: { + type: "doc", content: [ + { + type: "paragraph", + content: [{ + type: "dashField", + attrs: { + fieldKey: "src", + hideKey: false + } + }] + }, + { type: "paragraph" }, + { + type: "paragraph", + content: [{ + type: "dashField", + attrs: { + fieldKey: "dst", + hideKey: false + } + }] + }] + }, + selection: { type: "text", anchor: 1, head: 1 }, + storedMarks: [] + }; + linkTemplate.header = new RichTextField(JSON.stringify(rtf2), ""); + + doc["template-button-link"] = CurrentUserUtils.ficon({ + onDragStart: ScriptField.MakeFunction('makeDelegate(this.dragFactory)'), + dragFactory: new PrefetchProxy(linkTemplate) as any as Doc, + removeDropProperties: new List<string>(["dropAction"]), title: "link view", icon: "window-maximize" + }); + } + if (doc["template-button-switch"] === undefined) { const { FreeformDocument, MulticolumnDocument, TextDocument } = Docs.Create; @@ -179,17 +225,21 @@ export class CurrentUserUtils { }); } + const requiredTypes = [ + doc["template-button-slides"] as Doc, + doc["template-button-description"] as Doc, + doc["template-button-query"] as Doc, + doc["template-button-detail"] as Doc, + doc["template-button-link"] as Doc, + doc["template-button-switch"] as Doc]; if (doc["template-buttons"] === undefined) { - doc["template-buttons"] = new PrefetchProxy(Docs.Create.MasonryDocument([doc["template-button-slides"] as Doc, doc["template-button-description"] as Doc, - doc["template-button-query"] as Doc, doc["template-button-detail"] as Doc, doc["template-button-switch"] as Doc], { + doc["template-buttons"] = new PrefetchProxy(Docs.Create.MasonryDocument(requiredTypes, { title: "Advanced Item Prototypes", _xMargin: 0, _showTitle: "title", _autoHeight: true, _width: 500, columnWidth: 35, ignoreClick: true, lockedPosition: true, _chromeStatus: "disabled", dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }), })); } else { const curButnTypes = Cast(doc["template-buttons"], Doc, null); - const requiredTypes = [doc["template-button-slides"] as Doc, doc["template-button-description"] as Doc, - doc["template-button-query"] as Doc, doc["template-button-detail"] as Doc, doc["template-button-switch"] as Doc]; DocListCastAsync(curButnTypes.data).then(async curBtns => { await Promise.all(curBtns!); requiredTypes.map(btype => Doc.AddDocToList(curButnTypes, "data", btype)); @@ -554,8 +604,9 @@ export class CurrentUserUtils { } static setupCatalog(doc: Doc) { if (doc.myCatalog === undefined) { - doc.myCatalog = new PrefetchProxy(Docs.Create.TreeDocument([], { - title: "CATALOG", _height: 42, forceActive: true, boxShadow: "0 0", treeViewPreventOpen: false, lockedPosition: true, + doc.myCatalog = new PrefetchProxy(Docs.Create.SchemaDocument([], [], { + title: "CATALOG", _height: 1000, _fitWidth: true, forceActive: true, boxShadow: "0 0", treeViewPreventOpen: false, lockedPosition: true, + childDropAction: "alias", targetDropAction: "same", treeViewExpandedView: "layout" })); } return doc.myCatalog as Doc; @@ -583,10 +634,11 @@ export class CurrentUserUtils { if (doc["tabs-button-library"] === undefined) { doc["tabs-button-library"] = new PrefetchProxy(Docs.Create.ButtonDocument({ - _width: 50, _height: 25, title: "Library", _fontSize: 10, + _width: 50, _height: 25, title: "Library", _fontSize: 10, targetDropAction: "same", letterSpacing: "0px", textTransform: "unset", borderRounding: "5px 5px 0px 0px", boxShadow: "3px 3px 0px rgb(34, 34, 34)", sourcePanel: new PrefetchProxy(Docs.Create.TreeDocument([workspaces, documents, recentlyClosed, doc], { - title: "Library", _xMargin: 5, _yMargin: 5, _gridGap: 5, forceActive: true, childDropAction: "alias", lockedPosition: true, boxShadow: "0 0", dontRegisterChildViews: true + title: "Library", _xMargin: 5, _yMargin: 5, _gridGap: 5, forceActive: true, childDropAction: "alias", + lockedPosition: true, boxShadow: "0 0", dontRegisterChildViews: true, targetDropAction: "same" })) as any as Doc, targetContainer: new PrefetchProxy(sidebarContainer) as any as Doc, onClick: ScriptField.MakeScript("this.targetContainer.proto = this.sourcePanel;") diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index f1afaf734..597b72e0c 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -13,7 +13,7 @@ import * as globalCssVariables from "../views/globalCssVariables.scss"; import { UndoManager } from "./UndoManager"; import { SnappingManager } from "./SnappingManager"; -export type dropActionType = "alias" | "copy" | "move" | undefined; // undefined = move +export type dropActionType = "alias" | "copy" | "move" | "same" | undefined; // undefined = move export function SetupDrag( _reference: React.RefObject<HTMLElement>, docFunc: () => Doc | Promise<Doc> | undefined, @@ -37,7 +37,7 @@ export function SetupDrag( dragData.treeViewId = treeViewId; dragData.dontHideOnDrop = dontHideOnDrop; DragManager.StartDocumentDrag([_reference.current!], dragData, e.x, e.y); - dragStarted && dragStarted(); + dragStarted?.(); } }; const onRowUp = (): void => { @@ -122,7 +122,7 @@ export namespace DragManager { export class DocumentDragData { constructor(dragDoc: Doc[]) { this.draggedDocuments = dragDoc; - this.droppedDocuments = dragDoc; + this.droppedDocuments = []; this.offset = [0, 0]; } draggedDocuments: Doc[]; @@ -209,15 +209,19 @@ export namespace DragManager { }; const batch = UndoManager.StartBatch("dragging"); const finishDrag = (e: DragCompleteEvent) => { - e.docDragData && (e.docDragData.droppedDocuments = - dragData.draggedDocuments.map(d => !dragData.isSelectionMove && !dragData.userDropAction && ScriptCast(d.onDragStart) ? addAudioTag(ScriptCast(d.onDragStart).script.run({ this: d }).result) : - dragData.userDropAction === "alias" || (!dragData.userDropAction && dragData.dropAction === "alias") ? Doc.MakeAlias(d) : - dragData.userDropAction === "copy" || (!dragData.userDropAction && dragData.dropAction === "copy") ? Doc.MakeDelegate(d) : d) - ); - e.docDragData?.droppedDocuments.forEach((drop: Doc, i: number) => - (dragData?.removeDropProperties || []).concat(Cast(dragData.draggedDocuments[i].removeDropProperties, listSpec("string"), [])).map(prop => drop[prop] = undefined) - ); - batch.end(); + const docDragData = e.docDragData; + if (docDragData && !docDragData.droppedDocuments.length) { + docDragData.dropAction = dragData.userDropAction || dragData.dropAction; + docDragData.droppedDocuments = + dragData.draggedDocuments.map(d => !dragData.isSelectionMove && !dragData.userDropAction && ScriptCast(d.onDragStart) ? addAudioTag(ScriptCast(d.onDragStart).script.run({ this: d }).result) : + docDragData.dropAction === "alias" ? Doc.MakeAlias(d) : + docDragData.dropAction === "copy" ? Doc.MakeDelegate(d) : d); + docDragData.dropAction !== "same" && docDragData.droppedDocuments.forEach((drop: Doc, i: number) => + (dragData?.removeDropProperties || []).concat(Cast(dragData.draggedDocuments[i].removeDropProperties, listSpec("string"), [])).map(prop => drop[prop] = undefined) + ); + batch.end(); + } + return e; }; 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); @@ -231,6 +235,7 @@ export namespace DragManager { initialize?.(bd); Doc.GetProto(bd)["onClick-paramFieldKeys"] = new List<string>(params); e.docDragData && (e.docDragData.droppedDocuments = [bd]); + return e; }; StartDrag(eles, new DragManager.DocumentDragData([]), downX, downY, options, finishDrag); } @@ -319,7 +324,7 @@ export namespace DragManager { dragDiv = document.createElement("div"); dragDiv.className = "dragManager-dragDiv"; dragDiv.style.pointerEvents = "none"; - dragLabel = document.createElement("div") as HTMLDivElement; + dragLabel = document.createElement("div"); dragLabel.className = "dragManager-dragLabel"; dragLabel.style.zIndex = "100001"; dragLabel.style.fontSize = "10"; @@ -406,31 +411,28 @@ export namespace DragManager { const yFromTop = downY - elesCont.top; const xFromRight = elesCont.right - downX; const yFromBottom = elesCont.bottom - downY; - let alias = "alias"; const moveHandler = (e: PointerEvent) => { e.preventDefault(); // required or dragging text menu link item ends up dragging the link button as native drag/drop if (dragData instanceof DocumentDragData) { dragData.userDropAction = e.ctrlKey && e.altKey ? "copy" : e.ctrlKey ? "alias" : undefined; } - if (e) - if (e.shiftKey && dragData.droppedDocuments.length === 1) { - !dragData.dropAction && (dragData.dropAction = alias); - if (dragData.dropAction === "move") { - dragData.removeDocument?.(dragData.draggedDocuments[0]); - } - AbortDrag(); - finishDrag?.(new DragCompleteEvent(true, dragData)); - DragManager.StartWindowDrag?.({ - pageX: e.pageX, - pageY: e.pageY, - preventDefault: emptyFunction, - button: 0 - }, dragData.droppedDocuments); + if (e?.shiftKey && dragData.draggedDocuments.length === 1) { + dragData.dropAction = dragData.userDropAction || "same"; + if (dragData.dropAction === "move") { + dragData.removeDocument?.(dragData.draggedDocuments[0]); } + AbortDrag(); + finishDrag?.(new DragCompleteEvent(true, dragData)); + DragManager.StartWindowDrag?.({ + pageX: e.pageX, + pageY: e.pageY, + preventDefault: emptyFunction, + button: 0 + }, dragData.droppedDocuments); + } const { thisX, thisY } = snapDrag(e, xFromLeft, yFromTop, xFromRight, yFromBottom); - alias = "move"; const moveX = thisX - lastX; const moveY = thisY - lastY; lastX = thisX; diff --git a/src/client/views/DocComponent.tsx b/src/client/views/DocComponent.tsx index 3af570f1e..9b9a28f0f 100644 --- a/src/client/views/DocComponent.tsx +++ b/src/client/views/DocComponent.tsx @@ -1,4 +1,4 @@ -import { Doc, Opt, DataSym, DocListCast } from '../../fields/Doc'; +import { Doc, Opt, DataSym, DocListCast, AclSym, AclReadonly, AclAddonly } from '../../fields/Doc'; import { Touchable } from './Touchable'; import { computed, action, observable } from 'mobx'; import { Cast, BoolCast, ScriptCast } from '../../fields/Types'; @@ -138,9 +138,15 @@ export function ViewBoxAnnotatableComponent<P extends ViewBoxAnnotatableProps, T const docList = DocListCast(targetDataDoc[this.annotationKey]); const added = docs.filter(d => !docList.includes(d)); if (added.length) { - added.map(doc => doc.context = this.props.Document); - targetDataDoc[this.annotationKey] = new List<Doc>([...docList, ...added]); - targetDataDoc[this.annotationKey + "-lastModified"] = new DateField(new Date(Date.now())); + if (this.dataDoc[AclSym] === AclReadonly) { + return false; + } else if (this.dataDoc[AclSym] === AclAddonly) { + added.map(doc => Doc.AddDocToList(targetDataDoc, this.annotationKey, doc)); + } else { + added.map(doc => doc.context = this.props.Document); + targetDataDoc[this.annotationKey] = new List<Doc>([...docList, ...added]); + targetDataDoc[this.annotationKey + "-lastModified"] = new DateField(new Date(Date.now())); + } } return true; } diff --git a/src/client/views/EditableView.tsx b/src/client/views/EditableView.tsx index e0e205df9..e21d431b1 100644 --- a/src/client/views/EditableView.tsx +++ b/src/client/views/EditableView.tsx @@ -66,16 +66,17 @@ export class EditableView extends React.Component<EditableProps> { EditableView.loadId = ""; } - @action - componentDidUpdate(nextProps: EditableProps) { - // this is done because when autosuggest is turned on, the suggestions are passed in as a prop, - // so when the suggestions are passed in, and no editing prop is passed in, it used to set it - // to false. this will no longer do so -syip - if (nextProps.editing && nextProps.editing !== this._editing) { - this._editing = nextProps.editing; - EditableView.loadId = ""; - } - } + // @action + // componentDidUpdate(nextProps: EditableProps) { + // // this is done because when autosuggest is turned on, the suggestions are passed in as a prop, + // // so when the suggestions are passed in, and no editing prop is passed in, it used to set it + // // to false. this will no longer do so -syip + // console.log("props editing = " + nextProps.editing); + // if (nextProps.editing && nextProps.editing !== this._editing) { + // this._editing = nextProps.editing; + // EditableView.loadId = ""; + // } + // } _didShow = false; @@ -109,7 +110,7 @@ export class EditableView extends React.Component<EditableProps> { if (this._ref.current && this.props.showMenuOnLoad) { this.props.menuCallback?.(this._ref.current.getBoundingClientRect().x, this._ref.current.getBoundingClientRect().y); } else { - if (!this.props.onClick || !this.props.onClick(e)) { + if (!this.props.onClick?.(e)) { this._editing = true; this.props.isEditingCallback?.(true); } diff --git a/src/client/views/GestureOverlay.tsx b/src/client/views/GestureOverlay.tsx index 3bb80abd0..97df86168 100644 --- a/src/client/views/GestureOverlay.tsx +++ b/src/client/views/GestureOverlay.tsx @@ -809,11 +809,11 @@ export default class GestureOverlay extends Touchable { [this._strokes.map(l => { const b = this.getBounds(l); return <svg key={b.left} width={b.width} height={b.height} style={{ transform: `translate(${b.left}px, ${b.top}px)`, pointerEvents: "none", position: "absolute", zIndex: 30000, overflow: "visible" }}> - {InteractionUtils.CreatePolyline(l, b.left, b.top, ActiveInkColor(), ActiveInkWidth(), ActiveInkBezierApprox(), 1, 1, this.InkShape)} + {InteractionUtils.CreatePolyline(l, b.left, b.top, ActiveInkColor(), ActiveInkWidth(), ActiveInkBezierApprox(), 1, 1, this.InkShape, "none", false)} </svg>; }), this._points.length <= 1 ? (null) : <svg width={B.width} height={B.height} style={{ transform: `translate(${B.left}px, ${B.top}px)`, pointerEvents: "none", position: "absolute", zIndex: 30000, overflow: "visible" }}> - {InteractionUtils.CreatePolyline(this._points, B.left, B.top, ActiveInkColor(), ActiveInkWidth(), ActiveInkBezierApprox(), 1, 1, this.InkShape)} + {InteractionUtils.CreatePolyline(this._points, B.left, B.top, ActiveInkColor(), ActiveInkWidth(), ActiveInkBezierApprox(), 1, 1, this.InkShape, "none", false)} </svg>] ]; } diff --git a/src/client/views/collections/CollectionSchemaCells.tsx b/src/client/views/collections/CollectionSchemaCells.tsx index 62aed67ed..baf9d4156 100644 --- a/src/client/views/collections/CollectionSchemaCells.tsx +++ b/src/client/views/collections/CollectionSchemaCells.tsx @@ -1,5 +1,5 @@ import React = require("react"); -import { action, observable } from "mobx"; +import { action, observable, trace } from "mobx"; import { observer } from "mobx-react"; import { CellInfo } from "react-table"; import "react-table/react-table.css"; @@ -23,6 +23,7 @@ import { faExpand } from '@fortawesome/free-solid-svg-icons'; import { SchemaHeaderField } from "../../../fields/SchemaHeaderField"; import { undoBatch } from "../../util/UndoManager"; import { SnappingManager } from "../../util/SnappingManager"; +import { ComputedField } from "../../../fields/ScriptField"; library.add(faExpand); @@ -57,7 +58,6 @@ export class CollectionSchemaCell extends React.Component<CellProps> { componentDidMount() { document.addEventListener("keydown", this.onKeyDown); - } componentWillUnmount() { @@ -70,7 +70,6 @@ export class CollectionSchemaCell extends React.Component<CellProps> { document.removeEventListener("keydown", this.onKeyDown); this._isEditing = true; this.props.setIsEditing(true); - } } @@ -217,7 +216,8 @@ export class CollectionSchemaCell extends React.Component<CellProps> { // <div className="collectionSchemaView-cellContents-docExpander" onPointerDown={this.expandDoc} > // <FontAwesomeIcon icon="expand" size="sm" /> // </div> - // ); + // ); + trace(); return ( <div className="collectionSchemaView-cellContainer" style={{ cursor: fieldIsDoc ? "grab" : "auto" }} ref={dragRef} onPointerDown={this.onPointerDown} onPointerEnter={onPointerEnter} onPointerLeave={onPointerLeave}> @@ -231,23 +231,29 @@ export class CollectionSchemaCell extends React.Component<CellProps> { height={"auto"} maxHeight={Number(MAX_ROW_HEIGHT)} GetValue={() => { - const field = props.Document[props.fieldKey]; - if (Field.IsField(field)) { - return Field.toScriptString(field); - } - return ""; - } - } - SetValue={(value: string) => { + const cfield = ComputedField.WithoutComputed(() => FieldValue(props.Document[props.fieldKey])); + const cscript = cfield instanceof ComputedField ? cfield.script.originalScript : undefined; + const cfinalScript = cscript?.split("return")[cscript.split("return").length - 1]; + const val = cscript !== undefined ? `:=${cfinalScript?.substring(0, cfinalScript.length - 2)}` : + Field.IsField(cfield) ? Field.toScriptString(cfield) : ""; + return val; + }} + SetValue={action((value: string) => { + let retVal = false; if (value.startsWith(":=")) { - return this.props.setComputed(value.substring(2), props.Document, this.props.rowProps.column.id!, this.props.row, this.props.col); + retVal = this.props.setComputed(value.substring(2), props.Document, this.props.rowProps.column.id!, this.props.row, this.props.col); + } else { + const script = CompileScript(value, { requiredType: type, typecheck: false, editable: true, addReturn: true, params: { this: Doc.name, $r: "number", $c: "number", $: "any" } }); + if (script.compiled) { + retVal = this.applyToDoc(props.Document, this.props.row, this.props.col, script.run); + } } - const script = CompileScript(value, { requiredType: type, typecheck: false, editable: true, addReturn: true, params: { this: Doc.name, $r: "number", $c: "number", $: "any" } }); - if (!script.compiled) { - return false; + if (retVal) { + this._isEditing = false; // need to set this here. otherwise, the assignment of the field will invalidate & cause render() to be called with the wrong value for 'editing' + this.props.setIsEditing(false); } - return this.applyToDoc(props.Document, this.props.row, this.props.col, script.run); - }} + return retVal; + })} OnFillDown={async (value: string) => { const script = CompileScript(value, { requiredType: type, typecheck: false, editable: true, addReturn: true, params: { this: Doc.name, $r: "number", $c: "number", $: "any" } }); if (script.compiled) { diff --git a/src/client/views/collections/CollectionSchemaMovableTableHOC.tsx b/src/client/views/collections/CollectionSchemaMovableTableHOC.tsx index 6f1e8ac1f..b206765e8 100644 --- a/src/client/views/collections/CollectionSchemaMovableTableHOC.tsx +++ b/src/client/views/collections/CollectionSchemaMovableTableHOC.tsx @@ -66,8 +66,9 @@ export class MovableColumn extends React.Component<MovableColumnProps> { const rect = this._header!.current!.getBoundingClientRect(); const bounds = this.props.ScreenToLocalTransform().transformPoint(rect.left + ((rect.right - rect.left) / 2), rect.top); const before = x[0] < bounds[0]; - if (de.complete.columnDragData) { - this.props.reorderColumns(de.complete.columnDragData.colKey, this.props.columnValue, before, this.props.allColumns); + const colDragData = de.complete.columnDragData; + if (colDragData) { + this.props.reorderColumns(colDragData.colKey, this.props.columnValue, before, this.props.allColumns); return true; } return false; @@ -164,13 +165,14 @@ export class MovableRow extends React.Component<MovableRowProps> { } createRowDropTarget = (ele: HTMLDivElement) => { - this._rowDropDisposer && this._rowDropDisposer(); + this._rowDropDisposer?.(); if (ele) { this._rowDropDisposer = DragManager.MakeDropTarget(ele, this.rowDrop.bind(this)); } } rowDrop = (e: Event, de: DragManager.DropEvent) => { + this.onPointerLeave(e as any); const rowDoc = FieldValue(Cast(this.props.rowInfo.original, Doc)); if (!rowDoc) return false; @@ -203,10 +205,7 @@ export class MovableRow extends React.Component<MovableRowProps> { @action move: DragManager.MoveFunction = (doc: Doc | Doc[], targetCollection: Doc | undefined, addDoc) => { const targetView = targetCollection && DocumentManager.Instance.getDocumentView(targetCollection); - if (targetView && targetView.props.ContainingCollectionDoc) { - return doc !== targetCollection && doc !== targetView.props.ContainingCollectionDoc && this.props.removeDoc(doc) && addDoc(doc); - } - return doc !== targetCollection && this.props.removeDoc(doc) && addDoc(doc); + return doc !== targetCollection && doc !== targetView?.props.ContainingCollectionDoc && this.props.removeDoc(doc) && addDoc(doc); } render() { diff --git a/src/client/views/collections/CollectionSchemaView.tsx b/src/client/views/collections/CollectionSchemaView.tsx index 35f892d65..6dbee217a 100644 --- a/src/client/views/collections/CollectionSchemaView.tsx +++ b/src/client/views/collections/CollectionSchemaView.tsx @@ -28,7 +28,7 @@ import { CollectionSubView } from "./CollectionSubView"; import { CollectionView } from "./CollectionView"; import { ContentFittingDocumentView } from "../nodes/ContentFittingDocumentView"; import { setupMoveUpEvents, emptyFunction, returnZero, returnOne, returnFalse } from "../../../Utils"; -import { DocumentView } from "../nodes/DocumentView"; +import { SnappingManager } from "../../util/SnappingManager"; library.add(faCog, faPlus, faSortUp, faSortDown); library.add(faTable); @@ -186,7 +186,11 @@ export class CollectionSchemaView extends CollectionSubView(doc => doc) { } render() { - return <div className="collectionSchemaView-container"> + return <div className="collectionSchemaView-container" + style={{ + pointerEvents: !this.props.active() && !SnappingManager.GetIsDragging() ? "none" : undefined, + width: this.props.PanelWidth() || "100%", height: this.props.PanelHeight() || "100%" + }} > <div className="collectionSchemaView-tableContainer" style={{ width: `calc(100% - ${this.previewWidth()}px)` }} onPointerDown={this.onPointerDown} onWheel={e => this.props.active(true) && e.stopPropagation()} onDrop={e => this.onExternalDrop(e, {})} ref={this.createTarget}> {this.schemaTable} </div> @@ -651,7 +655,7 @@ export class SchemaTable extends React.Component<SchemaTableProps> { resized={this.resized} onResizedChange={this.onResizedChange} SubComponent={!hasCollectionChild ? undefined : row => (row.original.type !== "collection") ? (null) : - <div className="reactTable-sub"><SchemaTable {...this.props} Document={row.original} childDocs={undefined} /></div>} + <div className="reactTable-sub"><SchemaTable {...this.props} Document={row.original} dataDoc={undefined} childDocs={undefined} /></div>} />; } diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index e891c4274..180bcdd02 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -123,7 +123,7 @@ class TreeView extends React.Component<TreeViewProps> { protected createTreeDropTarget = (ele: HTMLDivElement) => { this._treedropDisposer?.(); - ele && (this._treedropDisposer = DragManager.MakeDropTarget(ele, this.treeDrop.bind(this)), this.props.document); + ele && (this._treedropDisposer = DragManager.MakeDropTarget(ele, this.treeDrop.bind(this), undefined, this.preTreeDrop.bind(this)), this.props.document); } onPointerEnter = (e: React.PointerEvent): void => { @@ -187,33 +187,36 @@ class TreeView extends React.Component<TreeViewProps> { })} />) + preTreeDrop = (e: Event, de: DragManager.DropEvent, targetAction: dropActionType) => { + const dragData = de.complete.docDragData; + dragData && (dragData.dropAction = this.props.treeViewId[Id] === dragData.treeViewId ? "same" : dragData.dropAction); + } + @undoBatch treeDrop = (e: Event, de: DragManager.DropEvent) => { const pt = [de.x, de.y]; const rect = this._header!.current!.getBoundingClientRect(); const before = pt[1] < rect.top + rect.height / 2; const inside = pt[0] > Math.min(rect.left + 75, rect.left + rect.width * .75) || (!before && this.treeViewOpen && DocListCast(this.dataDoc[this.fieldKey]).length); - if (de.complete.linkDragData) { - const sourceDoc = de.complete.linkDragData.linkSourceDocument; + const complete = de.complete; + if (complete.linkDragData) { + const sourceDoc = complete.linkDragData.linkSourceDocument; const destDoc = this.props.document; DocUtils.MakeLink({ doc: sourceDoc }, { doc: destDoc }, "tree link"); e.stopPropagation(); } - if (de.complete.docDragData) { + const docDragData = complete.docDragData; + if (docDragData) { e.stopPropagation(); - if (de.complete.docDragData.draggedDocuments[0] === this.props.document) return true; - let addDoc = (doc: Doc | Doc[]) => this.props.addDocument(doc, undefined, before); + if (docDragData.draggedDocuments[0] === this.props.document) return true; + const parentAddDoc = (doc: Doc | Doc[]) => this.props.addDocument(doc, undefined, before); + let addDoc = parentAddDoc; if (inside) { addDoc = (doc: Doc | Doc[]) => (doc instanceof Doc ? [doc] : doc).reduce( - ((flg: boolean, doc) => flg && Doc.AddDocToList(this.dataDoc, this.fieldKey, doc)), true) || addDoc(doc); + (flg: boolean, doc) => flg && Doc.AddDocToList(this.dataDoc, this.fieldKey, doc), true) || parentAddDoc(doc); } - const movedDocs = (de.complete.docDragData.treeViewId === this.props.treeViewId[Id] ? de.complete.docDragData.draggedDocuments : de.complete.docDragData.droppedDocuments); - const move = de.complete.docDragData.dropAction === "move" || de.complete.docDragData.dropAction; - return ((!move && (de.complete.docDragData.treeViewId !== this.props.treeViewId[Id])) || de.complete.docDragData.userDropAction) ? - de.complete.docDragData.droppedDocuments.reduce((added, d) => addDoc(d) || added, false) - : de.complete.docDragData.moveDocument ? - movedDocs.reduce((added, d) => de.complete.docDragData?.moveDocument?.(d, undefined, addDoc) || added, false) - : de.complete.docDragData.droppedDocuments.reduce((added, d) => addDoc(d), false); + const move = (!docDragData.dropAction || docDragData.dropAction === "move" || docDragData.dropAction === "same") && docDragData.moveDocument; + return docDragData.droppedDocuments.reduce((added, d) => (move ? docDragData.moveDocument?.(d, undefined, addDoc) : addDoc(d)) || added, false); } return false; } @@ -662,7 +665,16 @@ export class CollectionTreeView extends CollectionSubView<Document, Partial<coll protected createTreeDropTarget = (ele: HTMLDivElement) => { this.treedropDisposer?.(); if (this._mainEle = ele) { - this.treedropDisposer = DragManager.MakeDropTarget(ele, this.onInternalDrop.bind(this), this.props.Document); + this.treedropDisposer = DragManager.MakeDropTarget(ele, this.onInternalDrop.bind(this), this.props.Document, this.onInternalPreDrop.bind(this)); + } + } + + protected onInternalPreDrop = (e: Event, de: DragManager.DropEvent, targetAction: dropActionType) => { + const dragData = de.complete.docDragData; + if (dragData) { + if (targetAction && !dragData.draggedDocuments.some(d => d.context === this.props.Document && this.childDocs.includes(d))) { + dragData.dropAction = targetAction; + } else dragData.dropAction = this.props.Document[Id] === dragData?.treeViewId ? "same" : dragData.dropAction; } } @@ -788,7 +800,8 @@ export class CollectionTreeView extends CollectionSubView<Document, Partial<coll background: this.props.backgroundColor?.(this.props.Document), paddingLeft: `${NumCast(this.props.Document._xPadding, 10)}px`, paddingRight: `${NumCast(this.props.Document._xPadding, 10)}px`, - paddingTop: `${NumCast(this.props.Document._yPadding, 20)}px` + paddingTop: `${NumCast(this.props.Document._yPadding, 20)}px`, + pointerEvents: !this.props.active() && !SnappingManager.GetIsDragging() ? "none" : undefined }} onKeyPress={this.onKeyPress} onContextMenu={this.onContextMenu} diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index 00a1d27f0..9f5308ce8 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -42,6 +42,7 @@ import { CollectionStaffView } from './CollectionStaffView'; import { SubCollectionViewProps } from './CollectionSubView'; import { CollectionTimeView } from './CollectionTimeView'; import { CollectionTreeView } from "./CollectionTreeView"; +import { CollectionGridView } from './collectionGrid/CollectionGridView'; import './CollectionView.scss'; import { CollectionViewBaseChrome } from './CollectionViewChromes'; const higflyout = require("@hig/flyout"); @@ -67,6 +68,7 @@ export enum CollectionViewType { Linear = "linear", Staff = "staff", Map = "map", + Grid = "grid", Pile = "pileup" } export interface CollectionViewCustomProps { @@ -91,7 +93,7 @@ export interface CollectionRenderProps { export class CollectionView extends Touchable<FieldViewProps & CollectionViewCustomProps> { public static LayoutString(fieldStr: string) { return FieldView.LayoutString(CollectionView, fieldStr); } - private _isChildActive = false; //TODO should this be observable? + _isChildActive = false; //TODO should this be observable? get _isLightboxOpen() { return BoolCast(this.props.Document.isLightboxOpen); } set _isLightboxOpen(value) { this.props.Document.isLightboxOpen = value; } @observable private _curLightboxImg = 0; @@ -194,6 +196,7 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus case CollectionViewType.Masonry: { this.props.Document.singleColumn = false; return (<CollectionStackingView key="collview" {...props} />); } case CollectionViewType.Time: { return (<CollectionTimeView key="collview" {...props} />); } case CollectionViewType.Map: return (<CollectionMapView key="collview" {...props} />); + case CollectionViewType.Grid: return (<CollectionGridView key="gridview" {...props} />); case CollectionViewType.Freeform: default: { this.props.Document._freeformLayoutEngine = undefined; return (<CollectionFreeFormView key="collview" {...props} />); } } @@ -231,6 +234,7 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus subItems.push({ description: "Carousel", event: () => func(CollectionViewType.Carousel), icon: "columns" }); subItems.push({ description: "Pivot/Time", event: () => func(CollectionViewType.Time), icon: "columns" }); subItems.push({ description: "Map", event: () => func(CollectionViewType.Map), icon: "globe-americas" }); + subItems.push({ description: "Grid", event: () => func(CollectionViewType.Grid), icon: "th-list" }); if (addExtras && this.props.Document._viewType === CollectionViewType.Freeform) { subItems.push({ description: "Custom", icon: "fingerprint", event: AddCustomFreeFormLayout(this.props.Document, this.props.fieldKey) }); } @@ -240,7 +244,6 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus onContextMenu = (e: React.MouseEvent): void => { if (!e.isPropagationStopped() && this.props.Document[Id] !== CurrentUserUtils.MainDocId) { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7 - this.setupViewTypes("Add a Perspective...", vtype => { const newRendition = Doc.MakeAlias(this.props.Document); newRendition._viewType = vtype; diff --git a/src/client/views/collections/CollectionViewChromes.scss b/src/client/views/collections/CollectionViewChromes.scss index 03bd9a01a..f85cbfee2 100644 --- a/src/client/views/collections/CollectionViewChromes.scss +++ b/src/client/views/collections/CollectionViewChromes.scss @@ -3,7 +3,7 @@ .collectionViewChrome-cont { position: absolute; - width:100%; + width: 100%; opacity: 0.9; z-index: 9001; transition: top .5s; @@ -13,7 +13,7 @@ .collectionViewChrome { display: flex; padding-bottom: 1px; - height:32px; + height: 32px; border-bottom: .5px solid rgb(180, 180, 180); overflow: hidden; @@ -35,7 +35,7 @@ outline-color: black; } - .collectionViewBaseChrome-button{ + .collectionViewBaseChrome-button { font-size: 75%; text-transform: uppercase; letter-spacing: 2px; @@ -46,6 +46,7 @@ padding: 12px 10px 11px 10px; margin-left: 10px; } + .collectionViewBaseChrome-cmdPicker { margin-left: 3px; margin-right: 0px; @@ -54,15 +55,17 @@ border: none; color: grey; } + .commandEntry-outerDiv { pointer-events: all; background-color: gray; display: flex; flex-direction: row; - height:30px; + height: 30px; + .commandEntry-drop { - color:white; - width:25px; + color: white; + width: 25px; margin-top: auto; margin-bottom: auto; } @@ -76,15 +79,17 @@ pointer-events: all; // margin-top: 10px; } + .collectionViewBaseChrome-template, .collectionViewBaseChrome-viewModes { display: grid; background: rgb(238, 238, 238); - color:grey; - margin-top:auto; - margin-bottom:auto; + color: grey; + margin-top: auto; + margin-bottom: auto; margin-left: 5px; } + .collectionViewBaseChrome-viewModes { margin-left: 25px; } @@ -92,7 +97,7 @@ .collectionViewBaseChrome-viewSpecs { margin-left: 5px; display: grid; - + .collectionViewBaseChrome-filterIcon { position: relative; display: flex; @@ -163,13 +168,53 @@ } } - .collectionStackingViewChrome-cont, .collectionTreeViewChrome-cont { display: flex; justify-content: space-between; } + .collectionGridViewChrome-cont { + display: flex; + margin-left: 10; + + .collectionGridViewChrome-viewPicker { + font-size: 75%; + //text-transform: uppercase; + //letter-spacing: 2px; + background: rgb(238, 238, 238); + color: grey; + outline-color: black; + border: none; + //padding: 12px 10px 11px 10px; + } + + .collectionGridViewChrome-viewPicker:active { + outline-color: black; + } + + .grid-control { + align-self: center; + display: flex; + flex-direction: row; + margin-right: 5px; + + .grid-icon { + margin-right: 5px; + align-self: center; + } + + .flexLabel { + margin-bottom: 0; + } + } + + .collectionGridViewChrome-entryBox { + width: 50%; + } + } + + .collectionStackingViewChrome-sort, .collectionTreeViewChrome-sort { display: flex; @@ -199,13 +244,13 @@ .collectionTreeViewChrome-pivotField-label { vertical-align: center; padding-left: 10px; - margin:auto; + margin: auto; } .collectionStackingViewChrome-pivotField, .collectionTreeViewChrome-pivotField { color: white; - width:100%; + width: 100%; min-width: 100px; display: flex; align-items: center; @@ -215,7 +260,7 @@ input, .editableView-container-editing-oneLine, .editableView-container-editing { - margin:auto; + margin: auto; border: 0px; color: grey; text-align: center; @@ -236,6 +281,7 @@ .collectionTreeViewChrome-pivotField:hover { cursor: text; } + } } @@ -244,7 +290,10 @@ display: flex; position: relative; align-items: center; - .fwdKeyframe, .numKeyframe, .backKeyframe { + + .fwdKeyframe, + .numKeyframe, + .backKeyframe { cursor: pointer; position: absolute; width: 20; @@ -253,26 +302,31 @@ background: gray; display: flex; align-items: center; - color:white; + color: white; } + .backKeyframe { - left:0; + left: 0; + svg { - display:block; - margin:auto; + display: block; + margin: auto; } } + .numKeyframe { - left:20; + left: 20; display: flex; flex-direction: column; padding: 5px; } + .fwdKeyframe { - left:40; + left: 40; + svg { - display:block; - margin:auto; + display: block; + margin: auto; } } } @@ -334,8 +388,9 @@ flex-direction: column; height: 40px; } + .commandEntry-inputArea { - display:flex; + display: flex; flex-direction: row; width: 150px; margin: auto auto auto auto; diff --git a/src/client/views/collections/CollectionViewChromes.tsx b/src/client/views/collections/CollectionViewChromes.tsx index 3dc740c25..48810f1e9 100644 --- a/src/client/views/collections/CollectionViewChromes.tsx +++ b/src/client/views/collections/CollectionViewChromes.tsx @@ -1,8 +1,8 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { action, computed, observable, runInAction } from "mobx"; +import { action, computed, observable, runInAction, Lambda } from "mobx"; import { observer } from "mobx-react"; import * as React from "react"; -import { Doc, DocListCast } from "../../../fields/Doc"; +import { Doc, DocListCast, Opt } from "../../../fields/Doc"; import { Id } from "../../../fields/FieldSymbols"; import { List } from "../../../fields/List"; import { listSpec } from "../../../fields/Schema"; @@ -16,7 +16,6 @@ import { CollectionViewType } from "./CollectionView"; import { CollectionView } from "./CollectionView"; import "./CollectionViewChromes.scss"; import { CollectionFreeFormDocumentView } from "../nodes/CollectionFreeFormDocumentView"; -const datepicker = require('js-datepicker'); interface CollectionViewChromeProps { CollectionView: CollectionView; @@ -201,6 +200,7 @@ export class CollectionViewBaseChrome extends React.Component<CollectionViewChro case CollectionViewType.Schema: return (<CollectionSchemaViewChrome key="collchrome" PanelWidth={this.props.PanelWidth} CollectionView={this.props.CollectionView} type={this.props.type} />); case CollectionViewType.Tree: return (<CollectionTreeViewChrome key="collchrome" PanelWidth={this.props.PanelWidth} CollectionView={this.props.CollectionView} type={this.props.type} />); case CollectionViewType.Masonry: return (<CollectionStackingViewChrome key="collchrome" PanelWidth={this.props.PanelWidth} CollectionView={this.props.CollectionView} type={this.props.type} />); + case CollectionViewType.Grid: return (<CollectionGridViewChrome key="collchrome" PanelWidth={this.props.PanelWidth} CollectionView={this.props.CollectionView} type={this.props.type} />); default: return null; } } @@ -220,8 +220,9 @@ export class CollectionViewBaseChrome extends React.Component<CollectionViewChro @undoBatch @action protected drop(e: Event, de: DragManager.DropEvent): boolean { - if (de.complete.docDragData && de.complete.docDragData.draggedDocuments.length) { - this._buttonizableCommands.filter(c => c.title === this._currentKey).map(c => c.immediate(de.complete.docDragData?.draggedDocuments || [])); + const docDragData = de.complete.docDragData; + if (docDragData?.draggedDocuments.length) { + this._buttonizableCommands.filter(c => c.title === this._currentKey).map(c => c.immediate(docDragData.draggedDocuments || [])); e.stopPropagation(); } return true; @@ -562,3 +563,181 @@ export class CollectionTreeViewChrome extends React.Component<CollectionViewChro } } +/** + * Chrome for grid view. + */ +@observer +export class CollectionGridViewChrome extends React.Component<CollectionViewChromeProps> { + + private clicked: boolean = false; + private entered: boolean = false; + private decrementLimitReached: boolean = false; + @observable private resize = false; + private resizeListenerDisposer: Opt<Lambda>; + + componentDidMount() { + + runInAction(() => this.resize = this.props.CollectionView.props.PanelWidth() < 700); + + // listener to reduce text on chrome resize (panel resize) + this.resizeListenerDisposer = computed(() => this.props.CollectionView.props.PanelWidth()).observe(({ newValue }) => { + runInAction(() => this.resize = newValue < 700); + }); + } + + componentWillUnmount() { + this.resizeListenerDisposer?.(); + } + + get numCols() { return NumCast(this.props.CollectionView.props.Document.gridNumCols, 10); } + + /** + * Sets the value of `numCols` on the grid's Document to the value entered. + */ + @undoBatch + onNumColsEnter = (e: React.KeyboardEvent<HTMLInputElement>) => { + if (e.key === "Enter" || e.key === "Tab") { + if (e.currentTarget.valueAsNumber > 0) { + this.props.CollectionView.props.Document.gridNumCols = e.currentTarget.valueAsNumber; + } + + } + } + + /** + * Sets the value of `rowHeight` on the grid's Document to the value entered. + */ + // @undoBatch + // onRowHeightEnter = (e: React.KeyboardEvent<HTMLInputElement>) => { + // if (e.key === "Enter" || e.key === "Tab") { + // if (e.currentTarget.valueAsNumber > 0 && this.props.CollectionView.props.Document.rowHeight as number !== e.currentTarget.valueAsNumber) { + // this.props.CollectionView.props.Document.rowHeight = e.currentTarget.valueAsNumber; + // } + // } + // } + + /** + * Sets whether the grid is flexible or not on the grid's Document. + */ + @undoBatch + toggleFlex = () => { + this.props.CollectionView.props.Document.gridFlex = !BoolCast(this.props.CollectionView.props.Document.gridFlex, true); + } + + /** + * Increments the value of numCols on button click + */ + onIncrementButtonClick = () => { + this.clicked = true; + this.entered && (this.props.CollectionView.props.Document.gridNumCols as number)--; + undoBatch(() => this.props.CollectionView.props.Document.gridNumCols = this.numCols + 1)(); + this.entered = false; + } + + /** + * Decrements the value of numCols on button click + */ + onDecrementButtonClick = () => { + this.clicked = true; + if (!this.decrementLimitReached) { + this.entered && (this.props.CollectionView.props.Document.gridNumCols as number)++; + undoBatch(() => this.props.CollectionView.props.Document.gridNumCols = this.numCols - 1)(); + } + this.entered = false; + } + + /** + * Increments the value of numCols on button hover + */ + incrementValue = () => { + this.entered = true; + if (!this.clicked && !this.decrementLimitReached) { + this.props.CollectionView.props.Document.gridNumCols = this.numCols + 1; + } + this.decrementLimitReached = false; + this.clicked = false; + } + + /** + * Decrements the value of numCols on button hover + */ + decrementValue = () => { + this.entered = true; + if (!this.clicked) { + if (this.numCols !== 1) { + this.props.CollectionView.props.Document.gridNumCols = this.numCols - 1; + } + else { + this.decrementLimitReached = true; + } + } + + this.clicked = false; + } + + /** + * Toggles the value of preventCollision + */ + toggleCollisions = () => { + this.props.CollectionView.props.Document.gridPreventCollision = !this.props.CollectionView.props.Document.gridPreventCollision; + } + + /** + * Changes the value of the compactType + */ + changeCompactType = (e: React.ChangeEvent<HTMLSelectElement>) => { + // need to change startCompaction so that this operation will be undoable. + this.props.CollectionView.props.Document.gridStartCompaction = e.target.selectedOptions[0].value; + } + + render() { + return ( + <div className="collectionGridViewChrome-cont" > + <span className="grid-control" style={{ width: this.resize ? "25%" : "30%" }}> + <span className="grid-icon"> + <FontAwesomeIcon icon="columns" size="1x" /> + </span> + <input className="collectionGridViewChrome-entryBox" type="number" placeholder={this.numCols.toString()} onKeyDown={this.onNumColsEnter} onClick={(e: React.MouseEvent<HTMLInputElement, MouseEvent>) => { e.stopPropagation(); e.preventDefault(); e.currentTarget.focus(); }} /> + <input className="columnButton" onClick={this.onIncrementButtonClick} onMouseEnter={this.incrementValue} onMouseLeave={this.decrementValue} type="button" value="↑" /> + <input className="columnButton" style={{ marginRight: 5 }} onClick={this.onDecrementButtonClick} onMouseEnter={this.decrementValue} onMouseLeave={this.incrementValue} type="button" value="↓" /> + </span> + {/* <span className="grid-control"> + <span className="grid-icon"> + <FontAwesomeIcon icon="text-height" size="1x" /> + </span> + <input className="collectionGridViewChrome-entryBox" type="number" placeholder={this.props.CollectionView.props.Document.rowHeight as string} onKeyDown={this.onRowHeightEnter} onClick={(e: React.MouseEvent<HTMLInputElement, MouseEvent>) => { e.stopPropagation(); e.preventDefault(); e.currentTarget.focus(); }} /> + </span> */} + <span className="grid-control" style={{ width: this.resize ? "12%" : "20%" }}> + <input type="checkbox" style={{ marginRight: 5 }} onChange={this.toggleCollisions} checked={!this.props.CollectionView.props.Document.gridPreventCollision} /> + <label className="flexLabel">{this.resize ? "Coll" : "Collisions"}</label> + </span> + + <select className="collectionGridViewChrome-viewPicker" + style={{ marginRight: 5 }} + onPointerDown={stopPropagation} + onChange={this.changeCompactType} + value={StrCast(this.props.CollectionView.props.Document.gridStartCompaction, StrCast(this.props.CollectionView.props.Document.gridCompaction))}> + {["vertical", "horizontal", "none"].map(type => + <option className="collectionGridViewChrome-viewOption" + onPointerDown={stopPropagation} + value={type}> + {this.resize ? type[0].toUpperCase() + type.substring(1) : "Compact: " + type} + </option> + )} + </select> + + <span className="grid-control" style={{ width: this.resize ? "12%" : "20%" }}> + <input style={{ marginRight: 5 }} type="checkbox" onChange={this.toggleFlex} + checked={BoolCast(this.props.CollectionView.props.Document.gridFlex, true)} /> + <label className="flexLabel">{this.resize ? "Flex" : "Flexible"}</label> + </span> + + <button onClick={() => this.props.CollectionView.props.Document.gridResetLayout = true}> + {!this.resize ? "Reset" : + <FontAwesomeIcon icon="redo-alt" size="1x" />} + </button> + + </div> + ); + } +}
\ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx index f3fc04752..6cac39f77 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx @@ -46,10 +46,15 @@ export class CollectionFreeFormLinkView extends React.Component<CollectionFreeFo const bfield = afield === "anchor1" ? "anchor2" : "anchor1"; // really hacky stuff to make the LinkAnchorBox display where we want it to: - // if there's an element in the DOM with the id of the opposite anchor, then that DOM element is a hyperlink source for the current anchor and we want to place our link box at it's top right + // if there's an element in the DOM with a classname containing the link's id and a targetids attribute containing the other end of the link, + // then that DOM element is a hyperlink source for the current anchor and we want to place our link box at it's top right // otherwise, we just use the computed nearest point on the document boundary to the target Document - const targetAhyperlink = window.document.getElementById(this.props.LinkDocs[0][Id] + (this.props.LinkDocs[0][afield] as Doc)[Id]); - const targetBhyperlink = window.document.getElementById(this.props.LinkDocs[0][Id] + (this.props.LinkDocs[0][bfield] as Doc)[Id]); + const linkId = this.props.LinkDocs[0][Id]; // this link's Id + const AanchorId = (this.props.LinkDocs[0][afield] as Doc)[Id]; // anchor a's id + const BanchorId = (this.props.LinkDocs[0][bfield] as Doc)[Id]; // anchor b's id + const linkEles = Array.from(window.document.getElementsByClassName(linkId)); + const targetAhyperlink = linkEles.find((ele: any) => ele.getAttribute("targetids")?.includes(AanchorId)); + const targetBhyperlink = linkEles.find((ele: any) => ele.getAttribute("targetids")?.includes(BanchorId)); if (!targetBhyperlink) { this.props.A.props.Document[afield + "_x"] = (apt.point.x - abounds.left) / abounds.width * 100; this.props.A.props.Document[afield + "_y"] = (apt.point.y - abounds.top) / abounds.height * 100; diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index aee158a2a..cddac01ad 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -52,7 +52,6 @@ library.add(faEye as any, faTable, faPaintBrush, faExpandArrowsAlt, faCompressAr export const panZoomSchema = createSchema({ _panX: "number", _panY: "number", - scale: "number", currentTimecode: "number", displayTimecode: "number", currentFrame: "number", @@ -76,6 +75,7 @@ export type collectionFreeformViewProps = { forceScaling?: boolean; // whether to force scaling of content (needed by ImageBox) viewDefDivClick?: ScriptField; childPointerEvents?: boolean; + scaleField?: string; }; @observer @@ -108,6 +108,7 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P @computed get nativeWidth() { return this.fitToContent ? 0 : NumCast(this.Document._nativeWidth, this.props.NativeWidth()); } @computed get nativeHeight() { return this.fitToContent ? 0 : NumCast(this.Document._nativeHeight, this.props.NativeHeight()); } private get isAnnotationOverlay() { return this.props.isAnnotationOverlay; } + private get scaleFieldKey() { return this.props.scaleField || "scale"; } private get borderWidth() { return this.isAnnotationOverlay ? 0 : COLLECTION_BORDER_WIDTH; } private easing = () => this.props.Document.panTransformType === "Ease"; private panX = () => this.fitToContent ? (this.contentBounds.x + this.contentBounds.r) / 2 : this.Document._panX || 0; @@ -115,14 +116,14 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P private zoomScaling = () => (this.fitToContentScaling / this.parentScaling) * (this.fitToContent ? Math.min(this.props.PanelHeight() / (this.contentBounds.b - this.contentBounds.y), this.props.PanelWidth() / (this.contentBounds.r - this.contentBounds.x)) : - this.Document.scale || 1) + NumCast(this.Document[this.scaleFieldKey], 1)) @computed get cachedCenteringShiftX(): number { - const scaling = this.fitToContent ? 1 : this.contentScaling; + const scaling = this.fitToContent || !this.contentScaling ? 1 : this.contentScaling; return !this.isAnnotationOverlay ? this.props.PanelWidth() / 2 / this.parentScaling / scaling : 0; // shift so pan position is at center of window for non-overlay collections } @computed get cachedCenteringShiftY(): number { - const scaling = this.fitToContent ? 1 : this.contentScaling; + const scaling = this.fitToContent || !this.contentScaling ? 1 : this.contentScaling; return !this.isAnnotationOverlay ? this.props.PanelHeight() / 2 / this.parentScaling / scaling : 0;// shift so pan position is at center of window for non-overlay collections } @computed get cachedGetLocalTransform(): Transform { @@ -779,7 +780,7 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P if (localTransform.Scale >= 0.15 || localTransform.Scale > this.zoomScaling()) { const safeScale = Math.min(Math.max(0.15, localTransform.Scale), 40); - this.props.Document.scale = Math.abs(safeScale); + this.props.Document[this.scaleFieldKey] = Math.abs(safeScale); this.setPan(-localTransform.TranslateX / safeScale, -localTransform.TranslateY / safeScale); } } @@ -795,7 +796,7 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P if (!e.ctrlKey && MarqueeView.DragMarquee) this.setPan(this.panX() + e.deltaX, this.panY() + e.deltaY, "None", true); else this.zoom(e.clientX, e.clientY, e.deltaY); } - this.props.Document.targetScale = NumCast(this.props.Document.scale); + this.props.Document.targetScale = NumCast(this.props.Document[this.scaleFieldKey]); } @action @@ -852,7 +853,7 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P scaleAtPt(docpt: number[], scale: number) { const screenXY = this.getTransform().inverse().transformPoint(docpt[0], docpt[1]); this.Document.panTransformType = "Ease"; - this.layoutDoc.scale = scale; + this.layoutDoc[this.scaleFieldKey] = scale; const newScreenXY = this.getTransform().inverse().transformPoint(docpt[0], docpt[1]); const scrDelta = { x: screenXY[0] - newScreenXY[0], y: screenXY[1] - newScreenXY[1] }; const newpan = this.getTransform().transformDirection(scrDelta.x, scrDelta.y); @@ -896,7 +897,7 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P newState.initializers![this.Document[Id]] = { panX: newPanX, panY: newPanY }; HistoryUtil.pushState(newState); - const savedState = { px: this.Document._panX, py: this.Document._panY, s: this.Document.scale, pt: this.Document.panTransformType }; + const savedState = { px: this.Document._panX, py: this.Document._panY, s: this.Document[this.scaleFieldKey], pt: this.Document.panTransformType }; // if (!willZoom && DocumentView._focusHack.length) { // Doc.BrushDoc(this.props.Document); @@ -915,7 +916,7 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P if (afterFocus?.()) { this.Document._panX = savedState.px; this.Document._panY = savedState.py; - this.Document.scale = savedState.s; + this.Document[this.scaleFieldKey] = savedState.s; this.Document.panTransformType = savedState.pt; } }, 500); @@ -924,7 +925,7 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P } setScaleToZoom = (doc: Doc, scale: number = 0.75) => { - this.Document.scale = scale * Math.min(this.props.PanelWidth() / NumCast(doc._width), this.props.PanelHeight() / NumCast(doc._height)); + this.Document[this.scaleFieldKey] = scale * Math.min(this.props.PanelWidth() / NumCast(doc._width), this.props.PanelHeight() / NumCast(doc._height)); } @computed get libraryPath() { return this.props.LibraryPath ? [...this.props.LibraryPath, this.props.Document] : []; } @@ -1125,7 +1126,7 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P })); if (this.props.isAnnotationOverlay) { - this.props.Document.scale = Math.max(1, NumCast(this.props.Document.scale)); + this.props.Document[this.scaleFieldKey] = Math.max(1, NumCast(this.props.Document[this.scaleFieldKey])); } return elements; @@ -1206,7 +1207,7 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P const options = ContextMenu.Instance.findByDescription("Options..."); const optionItems: ContextMenuProps[] = options && "subitems" in options ? options.subitems : []; - optionItems.push({ description: "reset view", event: () => { this.props.Document._panX = this.props.Document._panY = 0; this.props.Document.scale = 1; }, icon: "compress-arrows-alt" }); + optionItems.push({ description: "reset view", event: () => { this.props.Document._panX = this.props.Document._panY = 0; this.props.Document[this.scaleFieldKey] = 1; }, icon: "compress-arrows-alt" }); optionItems.push({ description: "toggle snap line display", event: () => Doc.UserDoc().showSnapLines = !Doc.UserDoc().showSnapLines, icon: "compress-arrows-alt" }); optionItems.push({ description: "Reset default note style", event: () => Doc.UserDoc().defaultTextLayout = undefined, icon: "eye" }); optionItems.push({ description: (!this.layoutDoc._nativeWidth || !this.layoutDoc._nativeHeight ? "Freeze" : "Unfreeze") + " Aspect", event: this.toggleNativeDimensions, icon: "snowflake" }); diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx index 085625e69..5f09fa0ee 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -122,7 +122,7 @@ export class MarqueeView extends React.Component<SubCollectionViewProps & Marque FormattedTextBox.SelectOnLoadChar = FormattedTextBox.DefaultLayout ? e.key : ""; const tbox = Docs.Create.TextDocument("", { _width: 200, _height: 100, x: x, y: y, _autoHeight: true, _fontSize: NumCast(Doc.UserDoc().fontSize), - _fontFamily: StrCast(Doc.UserDoc().fontFamily), _backgroundColor: StrCast(Doc.UserDoc().backgroundColor), + _fontFamily: StrCast(Doc.UserDoc().fontFamily), title: "-typed text-" }); const template = FormattedTextBox.DefaultLayout; diff --git a/src/client/views/collections/collectionGrid/CollectionGridView.scss b/src/client/views/collections/collectionGrid/CollectionGridView.scss new file mode 100644 index 000000000..9c2d5cbff --- /dev/null +++ b/src/client/views/collections/collectionGrid/CollectionGridView.scss @@ -0,0 +1,160 @@ +.collectionGridView-contents { + display: flex; + overflow: hidden; + width: 100%; + height: 100%; + flex-direction: column; + + .collectionGridView-gridContainer { + height: 100%; + overflow-y: auto; + background-color: white; + overflow-x: hidden; + + display: flex; + flex-direction: row; + + .imageBox-cont img { + height: auto; + width: auto; + max-height: 100%; + max-width: 100%; + } + + .react-grid-layout { + width : 100%; + } + + .react-grid-item>.react-resizable-handle { + z-index: 4; // doesn't work on prezi otherwise + } + + .react-grid-item>.react-resizable-handle::after { + // grey so it can be seen on the audiobox + border-right: 2px solid slategrey; + border-bottom: 2px solid slategrey; + } + + .rowHeightSlider { + -webkit-appearance: none; + appearance: none; + width: 100%; + height: 15px; + background: #d3d3d3; + + position: absolute; + height: 3; + left: 5; + top: 30; + transform-origin: left; + transform: rotate(90deg); + outline: none; + opacity: 0.7; + } + + .rowHeightSlider:hover { + opacity: 1; + } + + .rowHeightSlider::-webkit-slider-thumb { + -webkit-appearance: none; + appearance: none; + width: 10px; + height: 10px; + border-radius: 50%; + background: darkgrey; + opacity: 1; + } + + .rowHeightSlider::-moz-range-thumb { + width: 10px; + height: 10px; + border-radius: 50%; + background: darkgrey; + opacity: 1; + } + } + + .collectionGridView-addDocumentButton { + display: flex; + overflow: hidden; + margin: auto; + width: 90%; + cursor: text; + min-height: 30px; + max-height: 30px; + font-size: 75%; + letter-spacing: 2px; + + .editableView-input { + outline-color: black; + letter-spacing: 2px; + color: grey; + border: 0px; + padding: 12px 10px 11px 10px; + } + + .editableView-container-editing, + .editableView-container-editing-oneLine { + display: flex; + align-items: center; + flex-direction: row; + height: 20px; + + width: 100%; + color: grey; + padding: 10px; + + span::before, + span::after { + content: ""; + width: 50%; + position: relative; + display: inline-block; + } + + span::before { + margin-right: 10px; + } + + span::after { + margin-left: 10px; + } + + span { + position: relative; + text-align: center; + white-space: nowrap; + overflow: visible; + display: flex; + color: gray; + align-items: center; + } + } + } + +} + +// .documentDecorations-container .documentDecorations-resizer { +// pointer-events: none; +// } + +// #documentDecorations-bottomRightResizer, +// #documentDecorations-bottomLeftResizer, +// #documentDecorations-topRightResizer, +// #documentDecorations-topLeftResizer { +// visibility: collapse; +// } + + +/* Chrome, Safari, Edge, Opera */ +input::-webkit-outer-spin-button, +input::-webkit-inner-spin-button { + -webkit-appearance: none; + margin: 0; +} + +/* Firefox */ +input[type=number] { + -moz-appearance: textfield; +}
\ No newline at end of file diff --git a/src/client/views/collections/collectionGrid/CollectionGridView.tsx b/src/client/views/collections/collectionGrid/CollectionGridView.tsx new file mode 100644 index 000000000..a5d355abc --- /dev/null +++ b/src/client/views/collections/collectionGrid/CollectionGridView.tsx @@ -0,0 +1,307 @@ +import { action, computed, Lambda, observable, reaction } from 'mobx'; +import { observer } from 'mobx-react'; +import * as React from "react"; +import { Doc, Opt } from '../../../../fields/Doc'; +import { documentSchema } from '../../../../fields/documentSchemas'; +import { Id } from '../../../../fields/FieldSymbols'; +import { makeInterface } from '../../../../fields/Schema'; +import { BoolCast, NumCast, ScriptCast, StrCast } from '../../../../fields/Types'; +import { emptyFunction, returnFalse, returnZero, setupMoveUpEvents } from '../../../../Utils'; +import { Docs } from '../../../documents/Documents'; +import { DragManager } from '../../../util/DragManager'; +import { SnappingManager } from '../../../util/SnappingManager'; +import { Transform } from '../../../util/Transform'; +import { undoBatch } from '../../../util/UndoManager'; +import { ContextMenu } from '../../ContextMenu'; +import { ContextMenuProps } from '../../ContextMenuItem'; +import { ContentFittingDocumentView } from '../../nodes/ContentFittingDocumentView'; +import { FormattedTextBox } from '../../nodes/formattedText/FormattedTextBox'; +import { CollectionSubView } from '../CollectionSubView'; +import "./CollectionGridView.scss"; +import Grid, { Layout } from "./Grid"; + +type GridSchema = makeInterface<[typeof documentSchema]>; +const GridSchema = makeInterface(documentSchema); + +@observer +export class CollectionGridView extends CollectionSubView(GridSchema) { + private _containerRef: React.RefObject<HTMLDivElement> = React.createRef(); + private _changeListenerDisposer: Opt<Lambda>; // listens for changes in this.childLayoutPairs + private _resetListenerDisposer: Opt<Lambda>; // listens for when the reset button is clicked + @observable private _rowHeight: Opt<number>; // temporary store of row height to make change undoable + @observable private _scroll: number = 0; // required to make sure the decorations box container updates on scroll + + @computed get onChildClickHandler() { return ScriptCast(this.Document.onChildClick); } + + @computed get numCols() { return NumCast(this.props.Document.gridNumCols, 10); } + @computed get rowHeight() { return this._rowHeight === undefined ? NumCast(this.props.Document.gridRowHeight, 100) : this._rowHeight; } + // sets the default width and height of the grid nodes + @computed get defaultW() { return NumCast(this.props.Document.gridDefaultW, 2); } + @computed get defaultH() { return NumCast(this.props.Document.gridDefaultH, 2); } + + @computed get colWidthPlusGap() { return (this.props.PanelWidth() - this.margin) / this.numCols; } + @computed get rowHeightPlusGap() { return this.rowHeight + this.margin; } + + @computed get margin() { return NumCast(this.props.Document.margin, 10); } // sets the margin between grid nodes + + @computed get flexGrid() { return BoolCast(this.props.Document.gridFlex, true); } // is grid static/flexible i.e. whether nodes be moved around and resized + @computed get compaction() { return StrCast(this.props.Document.gridStartCompaction, StrCast(this.props.Document.gridCompaction, "vertical")); } // is grid static/flexible i.e. whether nodes be moved around and resized + + componentDidMount() { + this._changeListenerDisposer = reaction(() => this.childLayoutPairs, (pairs) => { + const newLayouts: Layout[] = []; + const oldLayouts = this.savedLayoutList; + pairs.forEach((pair, i) => { + const existing = oldLayouts.find(l => l.i === pair.layout[Id]); + if (existing) newLayouts.push(existing); + else this.addLayoutItem(newLayouts, this.makeLayoutItem(pair.layout, this.unflexedPosition(i), !this.flexGrid)); + }); + pairs?.length && this.setLayoutList(newLayouts); + }, { fireImmediately: true }); + + // updates the layouts if the reset button has been clicked + this._resetListenerDisposer = reaction(() => this.props.Document.gridResetLayout, (reset) => { + if (reset && this.flexGrid) { + this.setLayout(this.childLayoutPairs.map((pair, index) => this.makeLayoutItem(pair.layout, this.unflexedPosition(index)))); + } + this.props.Document.gridResetLayout = false; + }); + } + + componentWillUnmount() { + this._changeListenerDisposer?.(); + this._resetListenerDisposer?.(); + } + + unflexedPosition(index: number): Omit<Layout, "i"> { + return { + x: (index % Math.floor(this.numCols / this.defaultW)) * this.defaultW, + y: Math.floor(index / Math.floor(this.numCols / this.defaultH)) * this.defaultH, + w: this.defaultW, + h: this.defaultH, + static: true + }; + } + + screenToCell(sx: number, sy: number) { + const pt = this.props.ScreenToLocalTransform().transformPoint(sx, sy); + const x = Math.floor(pt[0] / this.colWidthPlusGap); + const y = Math.floor((pt[1] + this._scroll) / this.rowHeight); + return { x, y }; + } + + makeLayoutItem = (doc: Doc, pos: { x: number, y: number }, Static: boolean = false, w: number = this.defaultW, h: number = this.defaultH) => { + return ({ i: doc[Id], w, h, x: pos.x, y: pos.y, static: Static }); + } + + addLayoutItem = (layouts: Layout[], layout: Layout) => { + const f = layouts.findIndex(l => l.i === layout.i); + f !== -1 && layouts.splice(f, 1); + layouts.push(layout); + return layouts; + } + /** + * @returns the transform that will correctly place the document decorations box. + */ + private lookupIndividualTransform = (layout: Layout) => { + const xypos = this.flexGrid ? layout : this.unflexedPosition(this.renderedLayoutList.findIndex(l => l.i === layout.i)); + const pos = { x: xypos.x * this.colWidthPlusGap + this.margin, y: xypos.y * this.rowHeightPlusGap + this.margin - this._scroll }; + + return this.props.ScreenToLocalTransform().translate(-pos.x, -pos.y); + } + + /** + * @returns the layout list converted from JSON + */ + get savedLayoutList() { + return (this.props.Document.gridLayoutString ? JSON.parse(StrCast(this.props.Document.gridLayoutString)) : []) as Layout[]; + } + + /** + * Stores the layout list on the Document as JSON + */ + setLayoutList(layouts: Layout[]) { + this.props.Document.gridLayoutString = JSON.stringify(layouts); + } + + /** + * + * @param layout + * @param dxf the x- and y-translations of the decorations box as a transform i.e. this.lookupIndividualTransform + * @param width + * @param height + * @returns the `ContentFittingDocumentView` of the node + */ + getDisplayDoc(layout: Doc, dxf: () => Transform, width: () => number, height: () => number) { + return <ContentFittingDocumentView + {...this.props} + Document={layout} + DataDoc={layout.resolvedDataDoc as Doc} + NativeHeight={returnZero} + NativeWidth={returnZero} + backgroundColor={this.props.backgroundColor} + ContainingCollectionDoc={this.props.Document} + PanelWidth={width} + PanelHeight={height} + ScreenToLocalTransform={dxf} + onClick={this.onChildClickHandler} + renderDepth={this.props.renderDepth + 1} + parentActive={this.props.active} + display={StrCast(this.props.Document.display, "contents")} // sets the css display type of the ContentFittingDocumentView component + />; + } + + /** + * Saves the layouts received from the Grid to the Document. + * @param layouts `Layout[]` + */ + @action + setLayout = (layoutArray: Layout[]) => { + // for every child in the collection, check to see if there's a corresponding grid layout object and + // updated layout object. If both exist, which they should, update the grid layout object from the updated object + if (this.flexGrid) { + const savedLayouts = this.savedLayoutList; + this.childLayoutPairs.forEach(({ layout: doc }) => { + const gridLayout = savedLayouts.find(gridLayout => gridLayout.i === doc[Id]); + gridLayout && Object.assign(gridLayout, layoutArray.find(layout => layout.i === doc[Id]) || gridLayout); + }); + + if (this.props.Document.gridStartCompaction) { + undoBatch(() => { + this.props.Document.gridCompaction = this.props.Document.gridStartCompaction; + this.setLayoutList(savedLayouts); + })(); + this.props.Document.gridStartCompaction = undefined; + } else { + undoBatch(() => this.setLayoutList(savedLayouts))(); + } + } + } + + /** + * @returns a list of `ContentFittingDocumentView`s inside wrapper divs. + * The key of the wrapper div must be the same as the `i` value of the corresponding layout. + */ + @computed + private get contents(): JSX.Element[] { + const collector: JSX.Element[] = []; + if (this.renderedLayoutList.length === this.childLayoutPairs.length) { + this.renderedLayoutList.forEach(l => { + const child = this.childLayoutPairs.find(c => c.layout[Id] === l.i); + const dxf = () => this.lookupIndividualTransform(l); + const width = () => (this.flexGrid ? l.w : this.defaultW) * this.colWidthPlusGap - this.margin; + const height = () => (this.flexGrid ? l.h : this.defaultH) * this.rowHeightPlusGap - this.margin; + child && collector.push( + <div key={child.layout[Id]} className={"document-wrapper" + (this.flexGrid && this.props.isSelected() ? "" : " static")} > + {this.getDisplayDoc(child.layout, dxf, width, height)} + </div > + ); + }); + } + return collector; + } + + /** + * @returns a list of `Layout` objects with attributes depending on whether the grid is flexible or static + */ + @computed get renderedLayoutList(): Layout[] { + return this.flexGrid ? + this.savedLayoutList.map(({ i, x, y, w, h }) => ({ + i, y, h, + x: x + w > this.numCols ? 0 : x, // handles wrapping around of nodes when numCols decreases + w: Math.min(w, this.numCols), // reduces width if greater than numCols + static: BoolCast(this.childLayoutPairs.find(({ layout }) => layout[Id] === i)?.layout.lockedPosition, false) // checks if the lock position item has been selected in the context menu + })) : + this.savedLayoutList.map((layout, index) => Object.assign(layout, this.unflexedPosition(index))); + } + + @action + onInternalDrop = (e: Event, de: DragManager.DropEvent) => { + const savedLayouts = this.savedLayoutList; + const dropped = de.complete.docDragData?.droppedDocuments; + if (dropped && super.onInternalDrop(e, de) && savedLayouts.length !== this.childDocs.length) { + dropped.forEach(doc => this.addLayoutItem(savedLayouts, this.makeLayoutItem(doc, this.screenToCell(de.x, de.y)))); // shouldn't place all docs in the same cell; + this.setLayoutList(savedLayouts); + return true; + } + return false; + } + + /** + * Handles the change in the value of the rowHeight slider. + */ + @action + onSliderChange = (event: React.ChangeEvent<HTMLInputElement>) => { + this._rowHeight = event.currentTarget.valueAsNumber; + } + @action + onSliderDown = (e: React.PointerEvent) => { + this._rowHeight = this.rowHeight; // uses _rowHeight during dragging and sets doc's rowHeight when finished so that operation is undoable + setupMoveUpEvents(this, e, returnFalse, action(() => { + undoBatch(() => this.props.Document.gridRowHeight = this._rowHeight)(); + this._rowHeight = undefined; + }), emptyFunction, false, false); + e.stopPropagation(); + } + /** + * Adds the display option to change the css display attribute of the `ContentFittingDocumentView`s + */ + onContextMenu = () => { + const displayOptionsMenu: ContextMenuProps[] = []; + displayOptionsMenu.push({ description: "Contents", event: () => this.props.Document.display = "contents", icon: "copy" }); + displayOptionsMenu.push({ description: "Undefined", event: () => this.props.Document.display = undefined, icon: "exclamation" }); + ContextMenu.Instance.addItem({ description: "Display", subitems: displayOptionsMenu, icon: "tv" }); + } + + onPointerDown = (e: React.PointerEvent) => { + if (this.props.active(true)) { + setupMoveUpEvents(this, e, returnFalse, returnFalse, + (e: PointerEvent, doubleTap?: boolean) => { + if (doubleTap) { + undoBatch(action(() => { + const text = Docs.Create.TextDocument("", { _width: 150, _height: 50 }); + FormattedTextBox.SelectOnLoad = text[Id];// track the new text box so we can give it a prop that tells it to focus itself when it's displayed + Doc.AddDocToList(this.props.Document, this.props.fieldKey, text); + this.setLayoutList(this.addLayoutItem(this.savedLayoutList, this.makeLayoutItem(text, this.screenToCell(e.clientX, e.clientY)))); + }))(); + } + }, + false); + if (this.props.isSelected(true)) e.stopPropagation(); + } + } + + render() { + return ( + <div className="collectionGridView-contents" ref={this.createDashEventsTarget} + style={{ pointerEvents: !this.props.active() && !SnappingManager.GetIsDragging() ? "none" : undefined }} + onContextMenu={this.onContextMenu} + onPointerDown={e => this.onPointerDown(e)} > + <div className="collectionGridView-gridContainer" ref={this._containerRef} + onWheel={e => e.stopPropagation()} + onScroll={action(e => { + if (!this.props.isSelected()) e.currentTarget.scrollTop = this._scroll; + else this._scroll = e.currentTarget.scrollTop; + })} > + <Grid + width={this.props.PanelWidth()} + nodeList={this.contents.length ? this.contents : null} + layout={this.contents.length ? this.renderedLayoutList : undefined} + childrenDraggable={this.props.isSelected() ? true : false} + numCols={this.numCols} + rowHeight={this.rowHeight} + setLayout={this.setLayout} + transformScale={this.props.ScreenToLocalTransform().Scale} + compactType={this.compaction} // determines whether nodes should remain in position, be bound to the top, or to the left + preventCollision={BoolCast(this.props.Document.gridPreventCollision)}// determines whether nodes should move out of the way (i.e. collide) when other nodes are dragged over them + margin={this.margin} + /> + <input className="rowHeightSlider" type="range" + style={{ width: this.props.PanelHeight() - 30 }} + min={1} value={this.rowHeight} max={this.props.PanelHeight() - 30} + onPointerDown={this.onSliderDown} onChange={this.onSliderChange} /> + </div> + </div > + ); + } +}
\ No newline at end of file diff --git a/src/client/views/collections/collectionGrid/Grid.tsx b/src/client/views/collections/collectionGrid/Grid.tsx new file mode 100644 index 000000000..3d2ed0cf9 --- /dev/null +++ b/src/client/views/collections/collectionGrid/Grid.tsx @@ -0,0 +1,53 @@ +import * as React from 'react'; +import { observer } from "mobx-react"; + +import "../../../../../node_modules/react-grid-layout/css/styles.css"; +import "../../../../../node_modules/react-resizable/css/styles.css"; + +import * as GridLayout from 'react-grid-layout'; +import { Layout } from 'react-grid-layout'; +export { Layout } from 'react-grid-layout'; + + +interface GridProps { + width: number; + nodeList: JSX.Element[] | null; + layout: Layout[] | undefined; + numCols: number; + rowHeight: number; + setLayout: (layout: Layout[]) => void; + transformScale: number; + childrenDraggable: boolean; + preventCollision: boolean; + compactType: string; + margin: number; +} + +/** + * Wrapper around the actual GridLayout of `react-grid-layout`. + */ +@observer +export default class Grid extends React.Component<GridProps> { + render() { + const compactType = this.props.compactType === "vertical" || this.props.compactType === "horizontal" ? this.props.compactType : null; + return ( + <GridLayout className="layout" + layout={this.props.layout} + cols={this.props.numCols} + rowHeight={this.props.rowHeight} + width={this.props.width} + compactType={compactType} + isDroppable={true} + isDraggable={this.props.childrenDraggable} + isResizable={this.props.childrenDraggable} + useCSSTransforms={true} + onLayoutChange={this.props.setLayout} + preventCollision={this.props.preventCollision} + transformScale={1 / this.props.transformScale} // still doesn't work :( + margin={[this.props.margin, this.props.margin]} + > + {this.props.nodeList} + </GridLayout> + ); + } +} diff --git a/src/client/views/nodes/ComparisonBox.tsx b/src/client/views/nodes/ComparisonBox.tsx index cce60628d..14a2c25bf 100644 --- a/src/client/views/nodes/ComparisonBox.tsx +++ b/src/client/views/nodes/ComparisonBox.tsx @@ -76,12 +76,12 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps, C const clearButton = (which: string) => { return <div className={`clear-button ${which}`} onPointerDown={e => e.stopPropagation()} // prevent triggering slider movement in registerSliding - onClick={e => this.clearDoc(e, `${which}Doc`)}> + onClick={e => this.clearDoc(e, `compareBox-${which}`)}> <FontAwesomeIcon className={`clear-button ${which}`} icon={"times"} size="sm" /> </div>; }; const displayDoc = (which: string) => { - const whichDoc = Cast(this.dataDoc[`${which}Doc`], Doc, null); + const whichDoc = Cast(this.dataDoc[`compareBox-${which}`], Doc, null); return whichDoc ? <> <ContentFittingDocumentView {...childProps} Document={whichDoc} /> {clearButton(which)} @@ -93,7 +93,7 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps, C const displayBox = (which: string, index: number, cover: number) => { return <div className={`${which}Box-cont`} key={which} style={{ width: this.props.PanelWidth() }} onPointerDown={e => this.registerSliding(e, cover)} - ref={ele => this.createDropTarget(ele, `${which}Doc`, index)} > + ref={ele => this.createDropTarget(ele, `compareBox-${which}`, index)} > {displayDoc(which)} </div>; }; diff --git a/src/client/views/nodes/ContentFittingDocumentView.tsx b/src/client/views/nodes/ContentFittingDocumentView.tsx index a90b4668e..ba075886b 100644 --- a/src/client/views/nodes/ContentFittingDocumentView.tsx +++ b/src/client/views/nodes/ContentFittingDocumentView.tsx @@ -1,15 +1,50 @@ import React = require("react"); import { computed } from "mobx"; import { observer } from "mobx-react"; +import { Transform } from "nodemailer/lib/xoauth2"; import "react-table/react-table.css"; -import { Doc, Opt, WidthSym, HeightSym } from "../../../fields/Doc"; -import { NumCast, StrCast, Cast } from "../../../fields/Types"; +import { Doc, HeightSym, Opt, WidthSym } from "../../../fields/Doc"; +import { ScriptField } from "../../../fields/ScriptField"; +import { Cast, NumCast, StrCast } from "../../../fields/Types"; import { TraceMobx } from "../../../fields/util"; -import { emptyFunction, returnOne } from "../../../Utils"; +import { emptyFunction } from "../../../Utils"; +import { dropActionType } from "../../util/DragManager"; +import { CollectionView } from "../collections/CollectionView"; import '../DocumentDecorations.scss'; import { DocumentView, DocumentViewProps } from "../nodes/DocumentView"; import "./ContentFittingDocumentView.scss"; +interface ContentFittingDocumentViewProps { + Document: Doc; + DataDocument?: Doc; + LayoutDoc?: () => Opt<Doc>; + NativeWidth?: () => number; + NativeHeight?: () => number; + FreezeDimensions?: boolean; + LibraryPath: Doc[]; + renderDepth: number; + fitToBox?: boolean; + layoutKey?: string; + dropAction?: dropActionType; + PanelWidth: () => number; + PanelHeight: () => number; + focus?: (doc: Doc) => void; + CollectionView?: CollectionView; + CollectionDoc?: Doc; + onClick?: ScriptField; + backgroundColor?: (doc: Doc) => string | undefined; + getTransform: () => Transform; + addDocument?: (document: Doc) => boolean; + moveDocument?: (document: Doc, target: Doc | undefined, addDoc: ((doc: Doc) => boolean)) => boolean; + removeDocument?: (document: Doc) => boolean; + active: (outsideReaction: boolean) => boolean; + whenActiveChanged: (isActive: boolean) => void; + addDocTab: (document: Doc, where: string) => boolean; + pinToPres: (document: Doc) => void; + dontRegisterView?: boolean; + rootSelected: (outsideReaction?: boolean) => boolean; + Display?: string; +} @observer export class ContentFittingDocumentView extends React.Component<DocumentViewProps>{ @@ -38,8 +73,8 @@ export class ContentFittingDocumentView extends React.Component<DocumentViewProp @computed get panelHeight() { return this.nativeHeight && !this.props.Document._fitWidth ? this.nativeHeight() * this.contentScaling() : this.props.PanelHeight(); } private getTransform = () => this.props.ScreenToLocalTransform().translate(-this.centeringOffset, -this.centeringYOffset).scale(1 / this.contentScaling()); - private get centeringOffset() { return this.nativeWidth() && !this.props.Document._fitWidth ? (this.props.PanelWidth() - this.nativeWidth() * this.contentScaling()) / 2 : 0; } - private get centeringYOffset() { return Math.abs(this.centeringOffset) < 0.001 ? (this.props.PanelHeight() - this.nativeHeight() * this.contentScaling()) / 2 : 0; } + private get centeringOffset() { return this.nativeWidth() && !this.props.Document._fitWidth && this.props.display !== "contents" ? (this.props.PanelWidth() - this.nativeWidth() * this.contentScaling()) / 2 : 0; } + private get centeringYOffset() { return Math.abs(this.centeringOffset) < 0.001 && this.props.display !== "contents" ? (this.props.PanelHeight() - this.nativeHeight() * this.contentScaling()) / 2 : 0; } @computed get borderRounding() { return StrCast(this.props.Document?.borderRounding); } @@ -47,7 +82,8 @@ export class ContentFittingDocumentView extends React.Component<DocumentViewProp TraceMobx(); return (<div className="contentFittingDocumentView" style={{ width: Math.abs(this.centeringYOffset) > 0.001 ? "auto" : this.props.PanelWidth(), - height: Math.abs(this.centeringOffset) > 0.0001 ? "auto" : this.props.PanelHeight() + height: Math.abs(this.centeringOffset) > 0.0001 ? "auto" : this.props.PanelHeight(), + display: this.props.display /* just added for grid */ }}> {!this.props.Document || !this.props.PanelWidth ? (null) : ( <div className="contentFittingDocumentView-previewDoc" diff --git a/src/client/views/nodes/DocHolderBox.tsx b/src/client/views/nodes/DocHolderBox.tsx index 0c5239d66..a4c4663dd 100644 --- a/src/client/views/nodes/DocHolderBox.tsx +++ b/src/client/views/nodes/DocHolderBox.tsx @@ -198,11 +198,10 @@ export class DocHolderBox extends ViewBoxAnnotatableComponent<FieldViewProps, Do @undoBatch @action drop = (e: Event, de: DragManager.DropEvent) => { - if (de.complete.docDragData) { - if (de.complete.docDragData.draggedDocuments[0].type === DocumentType.FONTICON) { - const doc = Cast(de.complete.docDragData.draggedDocuments[0].dragFactory, Doc, null); - this.layoutDoc.childLayoutTemplate = doc; - } + const docDragData = de.complete.docDragData; + if (docDragData?.draggedDocuments[0].type === DocumentType.FONTICON) { + const doc = Cast(docDragData.draggedDocuments[0].dragFactory, Doc, null); + this.layoutDoc.childLayoutTemplate = doc; } } protected createDropTarget = (ele: HTMLDivElement) => { diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 66bc73617..ccae9658f 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -96,6 +96,7 @@ export interface DocumentViewProps { dontRegisterView?: boolean; layoutKey?: string; radialMenu?: String[]; + display?: string; } @observer @@ -334,7 +335,7 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu this.props.addDocTab(alias, "onRight"); // UndoManager.RunInBatch(() => Doc.makeCustomViewClicked(this.props.Document, undefined, "onClick"), "edit onClick"); //ScriptBox.EditButtonScript("On Button Clicked ...", this.props.Document, "onClick", e.clientX, e.clientY), "on button click"); - } else if (this.Document.isLinkButton && !e.shiftKey && !e.ctrlKey) { + } else if (this.props.Document.links && this.Document.isLinkButton && !e.shiftKey && !e.ctrlKey) { DocListCast(this.props.Document.links).length && this.followLinkClick(e.altKey, e.ctrlKey, e.shiftKey); } else { if ((this.props.Document.onDragStart || (this.props.Document.rootDocument)) && !(e.ctrlKey || e.button > 0)) { // onDragStart implies a button doc that we don't want to select when clicking. RootDocument & isTEmplaetForField implies we're clicking on part of a template instance and we want to select the whole template, not the part @@ -516,6 +517,7 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu if (!(InteractionUtils.IsType(e, InteractionUtils.MOUSETYPE) || Doc.GetSelectedTool() === InkTool.Highlighter || Doc.GetSelectedTool() === InkTool.Pen)) { if (!InteractionUtils.IsType(e, InteractionUtils.PENTYPE)) { e.stopPropagation(); + if (SelectionManager.IsSelected(this, true) && this.props.Document._viewType !== CollectionViewType.Docking) e.preventDefault(); // goldenlayout needs to be able to move its tabs, so can't preventDefault for it // TODO: check here for panning/inking } return; @@ -529,8 +531,8 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu !e.ctrlKey && (e.button === 0 || InteractionUtils.IsType(e, InteractionUtils.TOUCHTYPE)) && !this.Document.inOverlay) { - e.stopPropagation(); // events stop at the lowest document that is active. if right dragging, we let it go through though to allow for context menu clicks. PointerMove callbacks should remove themselves if the move event gets stopPropagated by a lower-level handler (e.g, marquee drag); - + e.stopPropagation(); + if (SelectionManager.IsSelected(this, true) && this.props.Document._viewType !== CollectionViewType.Docking) e.preventDefault(); // goldenlayout needs to be able to move its tabs, so can't preventDefault for it } document.removeEventListener("pointermove", this.onPointerMove); document.removeEventListener("pointerup", this.onPointerUp); @@ -685,13 +687,30 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu @undoBatch @action setAcl = (acl: "readOnly" | "addOnly" | "ownerOnly") => { - this.layoutDoc.ACL = this.dataDoc.ACL = acl; + this.dataDoc.ACL = this.props.Document.ACL = acl; DocListCast(this.dataDoc[Doc.LayoutFieldKey(this.dataDoc)]).map(d => { if (d.author === Doc.CurrentUserEmail) d.ACL = acl; const data = d[DataSym]; if (data && data.author === Doc.CurrentUserEmail) data.ACL = acl; }); } + @undoBatch + @action + testAcl = (acl: "readOnly" | "addOnly" | "ownerOnly") => { + this.dataDoc.author = this.props.Document.author = "ADMIN"; + this.dataDoc.ACL = this.props.Document.ACL = acl; + DocListCast(this.dataDoc[Doc.LayoutFieldKey(this.dataDoc)]).map(d => { + if (d.author === Doc.CurrentUserEmail) { + d.author = "ADMIN"; + d.ACL = acl; + } + const data = d[DataSym]; + if (data && data.author === Doc.CurrentUserEmail) { + data.author = "ADMIN"; + data.ACL = acl; + } + }); + } @action onContextMenu = async (e: React.MouseEvent | Touch): Promise<void> => { @@ -756,6 +775,8 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu moreItems.push({ description: "Make Add Only", event: () => this.setAcl("addOnly"), icon: "concierge-bell" }); moreItems.push({ description: "Make Read Only", event: () => this.setAcl("readOnly"), icon: "concierge-bell" }); moreItems.push({ description: "Make Private", event: () => this.setAcl("ownerOnly"), icon: "concierge-bell" }); + moreItems.push({ description: "Test Private", event: () => this.testAcl("ownerOnly"), icon: "concierge-bell" }); + moreItems.push({ description: "Test Readonly", event: () => this.testAcl("readOnly"), icon: "concierge-bell" }); moreItems.push({ description: "Make View of Metadata Field", event: () => Doc.MakeMetadataFieldTemplate(this.props.Document, this.props.DataDoc), icon: "concierge-bell" }); moreItems.push({ description: `${this.Document._chromeStatus !== "disabled" ? "Hide" : "Show"} Chrome`, event: () => this.Document._chromeStatus = (this.Document._chromeStatus !== "disabled" ? "disabled" : "enabled"), icon: "project-diagram" }); moreItems.push({ description: this.Document.lockedPosition ? "Unlock Position" : "Lock Position", event: this.toggleLockPosition, icon: BoolCast(this.Document.lockedPosition) ? "unlock" : "lock" }); diff --git a/src/client/views/nodes/LinkAnchorBox.tsx b/src/client/views/nodes/LinkAnchorBox.tsx index 83245a89c..3c232eff8 100644 --- a/src/client/views/nodes/LinkAnchorBox.tsx +++ b/src/client/views/nodes/LinkAnchorBox.tsx @@ -117,7 +117,7 @@ export class LinkAnchorBox extends ViewBoxBaseComponent<FieldViewProps, LinkAnch const y = this.props.PanelWidth() > 1 ? NumCast(this.layoutDoc[this.fieldKey + "_y"], 100) : 0; const c = StrCast(this.layoutDoc.backgroundColor, "lightblue"); const anchor = this.fieldKey === "anchor1" ? "anchor2" : "anchor1"; - const anchorScale = (x === 0 || x === 100 || y === 0 || y === 100) ? 1 : .15; + const anchorScale = (x === 0 || x === 100 || y === 0 || y === 100) ? 1 : .25; const timecode = this.dataDoc[anchor + "_timecode"]; const targetTitle = StrCast((this.dataDoc[anchor] as Doc)?.title) + (timecode !== undefined ? ":" + timecode : ""); diff --git a/src/client/views/nodes/formattedText/DashFieldView.scss b/src/client/views/nodes/formattedText/DashFieldView.scss index 35ff9c1e6..23cf1e79b 100644 --- a/src/client/views/nodes/formattedText/DashFieldView.scss +++ b/src/client/views/nodes/formattedText/DashFieldView.scss @@ -25,7 +25,7 @@ margin-left: 2px; margin-right: 5px; position: relative; - display: inline-block; + display: inline; background-color: rgba(155, 155, 155, 0.24); span { min-width: 100%; diff --git a/src/client/views/nodes/formattedText/DashFieldView.tsx b/src/client/views/nodes/formattedText/DashFieldView.tsx index 9a1b909c1..60a9c2a27 100644 --- a/src/client/views/nodes/formattedText/DashFieldView.tsx +++ b/src/client/views/nodes/formattedText/DashFieldView.tsx @@ -103,11 +103,14 @@ export class DashFieldViewInternal extends React.Component<IDashFieldViewInterna // bcz: this is unfortunate, but since this React component is nested within a non-React text box (prosemirror), we can't // use React events. Essentially, React events occur after native events have been processed, so corresponding React events // will never fire because Prosemirror has handled the native events. So we add listeners for native events here. - return <span contentEditable={true} suppressContentEditableWarning={true} defaultValue={strVal} ref={r => { - r?.addEventListener("keydown", e => this.fieldSpanKeyDown(e, r)); - r?.addEventListener("blur", e => r && this.updateText(r.textContent!, false)); - r?.addEventListener("pointerdown", action((e) => this._showEnumerables = true)); - }} > + return <span className="dashFieldView-fieldSpan" contentEditable={true} + style={{ display: strVal.length < 2 ? "inline-block" : undefined }} + suppressContentEditableWarning={true} defaultValue={strVal} + ref={r => { + r?.addEventListener("keydown", e => this.fieldSpanKeyDown(e, r)); + r?.addEventListener("blur", e => r && this.updateText(r.textContent!, false)); + r?.addEventListener("pointerdown", action((e) => this._showEnumerables = true)); + }} > {strVal} </span>; } @@ -205,9 +208,9 @@ export class DashFieldViewInternal extends React.Component<IDashFieldViewInterna {this._fieldKey} </span>} - <div className="dashFieldView-fieldSpan"> - {this.fieldValueContent} - </div> + {/* <div className="dashFieldView-fieldSpan"> */} + {this.fieldValueContent} + {/* </div> */} {!this._showEnumerables ? (null) : <div className="dashFieldView-enumerables" onPointerDown={this.onPointerDownEnumerables} />} diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.scss b/src/client/views/nodes/formattedText/FormattedTextBox.scss index e608f9951..7b0ceb6cf 100644 --- a/src/client/views/nodes/formattedText/FormattedTextBox.scss +++ b/src/client/views/nodes/formattedText/FormattedTextBox.scss @@ -68,6 +68,7 @@ display: inline-block; position: absolute; right: 0; + overflow: hidden; .collectionfreeformview-container { position: relative; @@ -233,6 +234,48 @@ footnote::after { } } +.prosemirror-anchor { + overflow:hidden; + display:inline-grid; +} +.prosemirror-linkBtn { + background:unset; + color:unset; + padding:0; + text-transform: unset; + letter-spacing: unset; + font-size:unset; +} +.prosemirror-links { + display: none; + position: absolute; + background-color: gray; + padding-bottom: 10px; + margin-top: 1em; + z-index: 1; + } + .prosemirror-hrefoptions{ + width:0px; + border:unset; + padding:0px; + + } + + .prosemirror-links a { + float: left; + color: white; + text-decoration: none; + } + + .prosemirror-links a:hover { + background-color: #eee; + color: black; + } + + .prosemirror-anchor:hover .prosemirror-links { + display: grid; + } + .ProseMirror { touch-action: none; span { diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.tsx b/src/client/views/nodes/formattedText/FormattedTextBox.tsx index b0b648b66..1db50a5cc 100644 --- a/src/client/views/nodes/formattedText/FormattedTextBox.tsx +++ b/src/client/views/nodes/formattedText/FormattedTextBox.tsx @@ -283,8 +283,9 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp @undoBatch @action drop = async (e: Event, de: DragManager.DropEvent) => { - if (de.complete.docDragData) { - const draggedDoc = de.complete.docDragData.draggedDocuments.length && de.complete.docDragData.draggedDocuments[0]; + const dragData = de.complete.docDragData; + if (dragData) { + const draggedDoc = dragData.draggedDocuments.length && dragData.draggedDocuments[0]; // replace text contents whend dragging with Alt if (draggedDoc && draggedDoc.type === DocumentType.RTF && !Doc.AreProtosEqual(draggedDoc, this.props.Document) && de.altKey) { if (draggedDoc.data instanceof RichTextField) { @@ -292,8 +293,8 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp 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]; + } else if (dragData.userDropAction || dragData.embedDoc) { + const target = dragData.droppedDocuments[0]; // const link = DocUtils.MakeLink({ doc: this.dataDoc, ctx: this.props.ContainingCollectionDoc }, { doc: target }, "Embedded Doc:" + target.title); // if (link) { target._fitToBox = true; @@ -583,11 +584,22 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp }; } - makeLinkToSelection(linkDocId: string, title: string, location: string, targetDocId: string) { - if (this._editorView) { - const link = this._editorView.state.schema.marks.link.create({ href: Utils.prepend("/doc/" + linkDocId), title: title, location: location, linkId: linkDocId, targetId: targetDocId }); - this._editorView.dispatch(this._editorView.state.tr.removeMark(this._editorView.state.selection.from, this._editorView.state.selection.to, this._editorView.state.schema.marks.link). - addMark(this._editorView.state.selection.from, this._editorView.state.selection.to, link)); + makeLinkToSelection(linkId: string, title: string, location: string, targetId: string) { + const state = this._editorView?.state; + if (state) { + const href = Utils.prepend("/doc/" + linkId); + const sel = state.selection; + const splitter = state.schema.marks.splitter.create({ id: Utils.GenerateGuid() }); + let tr = state.tr.addMark(sel.from, sel.to, splitter); + sel.from !== sel.to && tr.doc.nodesBetween(sel.from, sel.to, (node: any, pos: number, parent: any) => { + if (node.firstChild === null && node.marks.find((m: Mark) => m.type.name === schema.marks.splitter.name)) { + const allHrefs = [{ href, title, targetId, linkId }]; + allHrefs.push(...(node.marks.find((m: Mark) => m.type.name === schema.marks.link.name)?.attrs.allHrefs ?? [])); + const link = state.schema.marks.link.create({ href, allHrefs, title, location, linkId, targetId }); + tr = tr.addMark(pos, pos + node.nodeSize, link); + } + }); + this._editorView!.dispatch(tr.removeMark(sel.from, sel.to, splitter)); } } componentDidMount() { @@ -695,7 +707,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp } const marks = [...node.marks]; const linkIndex = marks.findIndex(mark => mark.type === editor.state.schema.marks.link); - return linkIndex !== -1 && scrollToLinkID === marks[linkIndex].attrs.href.replace(/.*\/doc\//, "") ? node : undefined; + return linkIndex !== -1 && marks[linkIndex].attrs.allRefs.find((item: { href: string }) => scrollToLinkID === item.href.replace(/.*\/doc\//, "")) ? node : undefined; }; let start = 0; @@ -987,7 +999,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp FormattedTextBox._downEvent = false; if (!(e.nativeEvent as any).formattedHandled) { FormattedTextBoxComment.textBox = this; - FormattedTextBoxComment.update(this._editorView!); + FormattedTextBoxComment.update(this._editorView!, undefined, (e.target as any)?.className === "prosemirror-dropdownlink" ? (e.target as any).href : ""); } (e.nativeEvent as any).formattedHandled = true; @@ -1205,7 +1217,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp @computed get sidebarWidthPercent() { return StrCast(this.layoutDoc._sidebarWidthPercent, "0%"); } sidebarWidth = () => Number(this.sidebarWidthPercent.substring(0, this.sidebarWidthPercent.length - 1)) / 100 * this.props.PanelWidth(); - sidebarScreenToLocal = () => this.props.ScreenToLocalTransform().translate(-(this.props.PanelWidth() - this.sidebarWidth()), 0); + sidebarScreenToLocal = () => this.props.ScreenToLocalTransform().translate(-(this.props.PanelWidth() - this.sidebarWidth()) / this.props.ContentScaling(), 0); @computed get sidebarColor() { return StrCast(this.layoutDoc[this.props.fieldKey + "-backgroundColor"], StrCast(this.layoutDoc[this.props.fieldKey + "-backgroundColor"], "transparent")); } render() { TraceMobx(); @@ -1273,6 +1285,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp PanelWidth={this.sidebarWidth} NativeHeight={returnZero} NativeWidth={returnZero} + scaleField={this.annotationKey + "-scale"} annotationsKey={this.annotationKey} isAnnotationOverlay={false} focus={this.props.focus} diff --git a/src/client/views/nodes/formattedText/FormattedTextBoxComment.tsx b/src/client/views/nodes/formattedText/FormattedTextBoxComment.tsx index 59a6045ab..5ac173602 100644 --- a/src/client/views/nodes/formattedText/FormattedTextBoxComment.tsx +++ b/src/client/views/nodes/formattedText/FormattedTextBoxComment.tsx @@ -84,11 +84,13 @@ export class FormattedTextBoxComment { const keep = e.target && (e.target as any).type === "checkbox" ? true : false; const textBox = FormattedTextBoxComment.textBox; if (FormattedTextBoxComment.linkDoc && !keep && textBox) { - if (FormattedTextBoxComment.linkDoc.type !== DocumentType.LINK) { - textBox.props.addDocTab(FormattedTextBoxComment.linkDoc, e.ctrlKey ? "inTab" : "onRight"); - } else { - DocumentManager.Instance.FollowLink(FormattedTextBoxComment.linkDoc, textBox.props.Document, - (doc: Doc, followLinkLocation: string) => textBox.props.addDocTab(doc, e.ctrlKey ? "inTab" : followLinkLocation)); + if (FormattedTextBoxComment.linkDoc.author) { + if (FormattedTextBoxComment.linkDoc.type !== DocumentType.LINK) { + textBox.props.addDocTab(FormattedTextBoxComment.linkDoc, e.ctrlKey ? "inTab" : "onRight"); + } else { + DocumentManager.Instance.FollowLink(FormattedTextBoxComment.linkDoc, textBox.props.Document, + (doc: Doc, followLinkLocation: string) => textBox.props.addDocTab(doc, e.ctrlKey ? "inTab" : followLinkLocation)); + } } } else if (textBox && (FormattedTextBoxComment.tooltipText as any).href) { textBox.props.addDocTab(Docs.Create.WebDocument((FormattedTextBoxComment.tooltipText as any).href, { title: (FormattedTextBoxComment.tooltipText as any).href, _width: 200, _height: 400, UseCors: true }), "onRight"); @@ -115,7 +117,24 @@ export class FormattedTextBoxComment { FormattedTextBoxComment.tooltip && (FormattedTextBoxComment.tooltip.style.display = ""); } - static update(view: EditorView, lastState?: EditorState) { + static showCommentbox(set: string, view: EditorView, nbef: number) { + const state = view.state; + if (set !== "none") { + // These are in screen coordinates + // let start = view.coordsAtPos(state.selection.from), end = view.coordsAtPos(state.selection.to); + const start = view.coordsAtPos(state.selection.from - nbef), end = view.coordsAtPos(state.selection.from - nbef); + // The box in which the tooltip is positioned, to use as base + const box = (document.getElementsByClassName("mainView-container") as any)[0].getBoundingClientRect(); + // Find a center-ish x position from the selection endpoints (when + // crossing lines, end may be more to the left) + const left = Math.max((start.left + end.left) / 2, start.left + 3); + FormattedTextBoxComment.tooltip.style.left = (left - box.left) + "px"; + FormattedTextBoxComment.tooltip.style.bottom = (box.bottom - start.top) + "px"; + } + FormattedTextBoxComment.tooltip && (FormattedTextBoxComment.tooltip.style.display = set); + } + + static update(view: EditorView, lastState?: EditorState, forceUrl: string = "") { const state = view.state; // Don't do anything if the document/selection didn't change if (lastState && lastState.doc.eq(state.doc) && @@ -160,32 +179,34 @@ export class FormattedTextBoxComment { let child: any = null; state.doc.nodesBetween(state.selection.from, state.selection.to, (node: any, pos: number, parent: any) => !child && node.marks.length && (child = node)); const mark = child && findLinkMark(child.marks); - if (mark && child && nbef && naft && mark.attrs.showPreview) { - FormattedTextBoxComment.tooltipText.textContent = "external => " + mark.attrs.href; - (FormattedTextBoxComment.tooltipText as any).href = mark.attrs.href; - if (mark.attrs.href.startsWith("https://en.wikipedia.org/wiki/")) { - wiki().page(mark.attrs.href.replace("https://en.wikipedia.org/wiki/", "")).then(page => page.summary().then(summary => FormattedTextBoxComment.tooltipText.textContent = summary.substring(0, 500))); + const href = mark?.attrs.allHrefs.find((item: { href: string }) => item.href)?.href || forceUrl; + if (forceUrl || (href && child && nbef && naft && mark?.attrs.showPreview)) { + FormattedTextBoxComment.tooltipText.textContent = "external => " + href; + (FormattedTextBoxComment.tooltipText as any).href = href; + if (href.startsWith("https://en.wikipedia.org/wiki/")) { + wiki().page(href.replace("https://en.wikipedia.org/wiki/", "")).then(page => page.summary().then(summary => FormattedTextBoxComment.tooltipText.textContent = summary.substring(0, 500))); } else { FormattedTextBoxComment.tooltipText.style.whiteSpace = "pre"; FormattedTextBoxComment.tooltipText.style.overflow = "hidden"; } - if (mark.attrs.href.indexOf(Utils.prepend("/doc/")) === 0) { + if (href.indexOf(Utils.prepend("/doc/")) === 0) { FormattedTextBoxComment.tooltipText.textContent = "target not found..."; (FormattedTextBoxComment.tooltipText as any).href = ""; - const docTarget = mark.attrs.href.replace(Utils.prepend("/doc/"), "").split("?")[0]; + const docTarget = href.replace(Utils.prepend("/doc/"), "").split("?")[0]; try { ReactDOM.unmountComponentAtNode(FormattedTextBoxComment.tooltipText); } catch (e) { } docTarget && DocServer.GetRefField(docTarget).then(async linkDoc => { if (linkDoc instanceof Doc) { - (FormattedTextBoxComment.tooltipText as any).href = mark.attrs.href; + (FormattedTextBoxComment.tooltipText as any).href = href; FormattedTextBoxComment.linkDoc = linkDoc; const anchor = FieldValue(Doc.AreProtosEqual(FieldValue(Cast(linkDoc.anchor1, Doc)), textBox.dataDoc) ? Cast(linkDoc.anchor2, Doc) : (Cast(linkDoc.anchor1, Doc)) || linkDoc); const target = anchor?.annotationOn ? await DocCastAsync(anchor.annotationOn) : anchor; if (anchor !== target && anchor && target) { target._scrollY = NumCast(anchor?.y); } - if (target) { + if (target?.author) { + FormattedTextBoxComment.showCommentbox("", view, nbef); ReactDOM.render(<ContentFittingDocumentView Document={target} LibraryPath={emptyPath} @@ -223,19 +244,7 @@ export class FormattedTextBoxComment { set = ""; } } - if (set !== "none") { - // These are in screen coordinates - // let start = view.coordsAtPos(state.selection.from), end = view.coordsAtPos(state.selection.to); - const start = view.coordsAtPos(state.selection.from - nbef), end = view.coordsAtPos(state.selection.from - nbef); - // The box in which the tooltip is positioned, to use as base - const box = (document.getElementsByClassName("mainView-container") as any)[0].getBoundingClientRect(); - // Find a center-ish x position from the selection endpoints (when - // crossing lines, end may be more to the left) - const left = Math.max((start.left + end.left) / 2, start.left + 3); - FormattedTextBoxComment.tooltip.style.left = (left - box.left) + "px"; - FormattedTextBoxComment.tooltip.style.bottom = (box.bottom - start.top) + "px"; - } - FormattedTextBoxComment.tooltip && (FormattedTextBoxComment.tooltip.style.display = set); + FormattedTextBoxComment.showCommentbox(set, view, nbef); } destroy() { } diff --git a/src/client/views/nodes/formattedText/ProsemirrorExampleTransfer.ts b/src/client/views/nodes/formattedText/ProsemirrorExampleTransfer.ts index 0e3e7f91e..77b93b9d2 100644 --- a/src/client/views/nodes/formattedText/ProsemirrorExampleTransfer.ts +++ b/src/client/views/nodes/formattedText/ProsemirrorExampleTransfer.ts @@ -6,7 +6,6 @@ import { liftListItem, sinkListItem } from "./prosemirrorPatches.js"; import { splitListItem, wrapInList, } from "prosemirror-schema-list"; import { EditorState, Transaction, TextSelection } from "prosemirror-state"; import { SelectionManager } from "../../../util/SelectionManager"; -import { Docs } from "../../../documents/Documents"; import { NumCast, BoolCast, Cast, StrCast } from "../../../../fields/Types"; import { Doc } from "../../../../fields/Doc"; import { FormattedTextBox } from "./FormattedTextBox"; diff --git a/src/client/views/nodes/formattedText/RichTextMenu.tsx b/src/client/views/nodes/formattedText/RichTextMenu.tsx index fd1b26208..03d393cde 100644 --- a/src/client/views/nodes/formattedText/RichTextMenu.tsx +++ b/src/client/views/nodes/formattedText/RichTextMenu.tsx @@ -631,7 +631,7 @@ export default class RichTextMenu extends AntimodeMenu { const node = this.view.state.selection.$from.nodeAfter; const link = node && node.marks.find(m => m.type.name === "link"); if (link) { - const href = link.attrs.href; + const href = link.attrs.allHrefs.length > 0 ? link.attrs.allHrefs[0].href : undefined; if (href) { if (href.indexOf(Utils.prepend("/doc/")) === 0) { const linkclicked = href.replace(Utils.prepend("/doc/"), "").split("?")[0]; @@ -677,7 +677,7 @@ export default class RichTextMenu extends AntimodeMenu { const node = this.view.state.selection.$from.nodeAfter; const link = node && node.marks.find(m => m.type === this.view!.state.schema.marks.link); - const href = link!.attrs.href; + const href = link!.attrs.allHrefs.length > 0 ? link!.attrs.allHrefs[0].href : undefined; if (href) { if (href.indexOf(Utils.prepend("/doc/")) === 0) { const linkclicked = href.replace(Utils.prepend("/doc/"), "").split("?")[0]; @@ -705,8 +705,8 @@ export default class RichTextMenu extends AntimodeMenu { let startIndex = $start.index(); let endIndex = $start.indexAfter(); - while (startIndex > 0 && $start.parent.child(startIndex - 1).marks.filter(m => m.type === mark && m.attrs.href === href).length) startIndex--; - while (endIndex < $start.parent.childCount && $start.parent.child(endIndex).marks.filter(m => m.type === mark && m.attrs.href === href).length) endIndex++; + while (startIndex > 0 && $start.parent.child(startIndex - 1).marks.filter(m => m.type === mark && m.attrs.allHrefs.find((item: { href: string }) => item.href === href)).length) startIndex--; + while (endIndex < $start.parent.childCount && $start.parent.child(endIndex).marks.filter(m => m.type === mark && m.attrs.allHrefs.find((item: { href: string }) => item.href === href)).length) endIndex++; let startPos = $start.start(); let endPos = startPos; diff --git a/src/client/views/nodes/formattedText/marks_rts.ts b/src/client/views/nodes/formattedText/marks_rts.ts index ebaa23e99..c735155d8 100644 --- a/src/client/views/nodes/formattedText/marks_rts.ts +++ b/src/client/views/nodes/formattedText/marks_rts.ts @@ -9,14 +9,20 @@ const codeDOM: DOMOutputSpecArray = ["code", 0]; // :: Object [Specs](#model.MarkSpec) for the marks in the schema. export const marks: { [index: string]: MarkSpec } = { + splitter: { + attrs: { + id: { default: "" } + }, + toDOM(node: any) { + return ["div", { className: "dummy" }, 0]; + } + }, // :: MarkSpec A link. Has `href` and `title` attributes. `title` // defaults to the empty string. Rendered and parsed as an `<a>` // element. link: { attrs: { - href: {}, - targetId: { default: "" }, - linkId: { default: "" }, + allHrefs: { default: [] as { href: string, title: string, linkId: string, targetId: string }[] }, showPreview: { default: true }, location: { default: null }, title: { default: null }, @@ -25,13 +31,25 @@ export const marks: { [index: string]: MarkSpec } = { inclusive: false, parseDOM: [{ tag: "a[href]", getAttrs(dom: any) { - return { href: dom.getAttribute("href"), location: dom.getAttribute("location"), title: dom.getAttribute("title"), targetId: dom.getAttribute("id") }; + return { allHrefs: [{ href: dom.getAttribute("href"), title: dom.getAttribute("title"), linkId: dom.getAttribute("linkids"), targetId: dom.getAttribute("targetids") }], location: dom.getAttribute("location"), }; } }], toDOM(node: any) { + const targetids = node.attrs.allHrefs.reduce((p: string, item: { href: string, title: string, targetId: string, linkId: string }) => p + " " + item.targetId, ""); + const linkids = node.attrs.allHrefs.reduce((p: string, item: { href: string, title: string, targetId: string, linkId: string }) => p + " " + item.linkId, ""); return node.attrs.docref && node.attrs.title ? ["div", ["span", `"`], ["span", 0], ["span", `"`], ["br"], ["a", { ...node.attrs, class: "prosemirror-attribution", title: `${node.attrs.title}` }, node.attrs.title], ["br"]] : - ["a", { ...node.attrs, id: node.attrs.linkId + node.attrs.targetId, title: `${node.attrs.title}` }, 0]; + node.attrs.allHrefs.length === 1 ? + ["a", { ...node.attrs, class: linkids, targetids, title: `${node.attrs.title}`, href: node.attrs.allHrefs[0].href }, 0] : + ["div", { class: "prosemirror-anchor" }, + ["button", { class: "prosemirror-linkBtn" }, + ["a", { ...node.attrs, class: linkids, targetids, title: `${node.attrs.title}` }, 0], + ["input", { class: "prosemirror-hrefoptions" }], + ], + ["div", { class: "prosemirror-links" }, ...node.attrs.allHrefs.map((item: { href: string, title: string }) => + ["a", { class: "prosemirror-dropdownlink", href: item.href }, item.title] + )] + ]; } }, diff --git a/src/fields/Doc.ts b/src/fields/Doc.ts index ffef9a384..b205a4a10 100644 --- a/src/fields/Doc.ts +++ b/src/fields/Doc.ts @@ -100,7 +100,7 @@ export const UpdatingFromServer = Symbol("UpdatingFromServer"); const CachedUpdates = Symbol("Cached updates"); -function fetchProto(doc: Doc) { +export function fetchProto(doc: Doc) { if (doc.author !== Doc.CurrentUserEmail) { const acl = Doc.Get(doc, "ACL", true); switch (acl) { @@ -116,21 +116,9 @@ function fetchProto(doc: Doc) { } } - const proto = doc.proto; - if (proto instanceof Promise) { - proto.then(proto => { - if (proto.author !== Doc.CurrentUserEmail) { - if (proto.ACL === "ownerOnly") { - proto[AclSym] = doc[AclSym] = AclPrivate; - return undefined; - } else if (proto.ACL === "readOnly") { - proto[AclSym] = doc[AclSym] = AclReadonly; - } else if (proto.ACL === "addOnly") { - proto[AclSym] = doc[AclSym] = AclAddonly; - } - } - }); - return proto; + if (doc.proto instanceof Promise) { + doc.proto.then(proto => fetchProto(proto)); + return doc.proto; } } @@ -442,7 +430,8 @@ export namespace Doc { if (allowDuplicates !== true) { const pind = list.reduce((l, d, i) => d instanceof Doc && d[Id] === doc[Id] ? i : l, -1); if (pind !== -1) { - list.splice(pind, 1); + return true; + //list.splice(pind, 1); // bcz: this causes schemaView docs in the Catalog to move to the bottom of the schema view when they are dragged even though they haven't left the collection } } if (first) { diff --git a/src/fields/RichTextUtils.ts b/src/fields/RichTextUtils.ts index f81ec8c6d..66959882d 100644 --- a/src/fields/RichTextUtils.ts +++ b/src/fields/RichTextUtils.ts @@ -392,7 +392,7 @@ export namespace RichTextUtils { const { attrs } = mark; switch (converted) { case "link": - let url = attrs.href; + let url = attrs.allHrefs.length ? attrs.allHrefs[0].href : ""; const delimiter = "/doc/"; const alreadyShared = "?sharing=true"; if (new RegExp(window.location.origin + delimiter).test(url) && !url.endsWith(alreadyShared)) { diff --git a/src/mobile/MobileInkOverlay.tsx b/src/mobile/MobileInkOverlay.tsx index 1b3388161..d668d134e 100644 --- a/src/mobile/MobileInkOverlay.tsx +++ b/src/mobile/MobileInkOverlay.tsx @@ -112,7 +112,8 @@ export default class MobileInkOverlay extends React.Component { altKey: false, metaKey: false, ctrlKey: false, - shiftKey: false + shiftKey: false, + embedKey: false } } ) diff --git a/src/mobile/MobileInterface.tsx b/src/mobile/MobileInterface.tsx index 979094dda..25dc9fd55 100644 --- a/src/mobile/MobileInterface.tsx +++ b/src/mobile/MobileInterface.tsx @@ -12,9 +12,8 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { action, computed, observable } from 'mobx'; import { observer } from 'mobx-react'; import * as rp from 'request-promise'; -import { Doc, DocListCast, FieldResult } from '../fields/Doc'; -import { Id } from '../fields/FieldSymbols'; -import { FieldValue, Cast, StrCast } from '../fields/Types'; +import { Doc, DocListCast } from '../fields/Doc'; +import { FieldValue, Cast } from '../fields/Types'; import { CurrentUserUtils } from '../client/util/CurrentUserUtils'; import { emptyPath, emptyFunction, returnFalse, returnOne, returnTrue, returnZero, Utils } from '../Utils'; import { DocServer } from '../client/DocServer'; @@ -22,7 +21,6 @@ import { Docs } from '../client/documents/Documents'; import { Scripting } from '../client/util/Scripting'; import { DocumentView } from '../client/views/nodes/DocumentView'; import { Transform } from '../client/util/Transform'; -// import { InkingControl } from '../client/views/InkingControl'; import "./MobileInterface.scss"; import "./MobileMenu.scss"; import "./MobileHome.scss"; @@ -33,13 +31,10 @@ import { Uploader } from "./ImageUpload"; import { DockedFrameRenderer } from '../client/views/collections/CollectionDockingView'; import { InkTool } from '../fields/InkField'; import { listSpec } from '../fields/Schema'; -import { nullAudio, WebField } from '../fields/URLField'; +import { nullAudio } from '../fields/URLField'; import GestureOverlay from "../client/views/GestureOverlay"; -import { SelectionManager } from "../client/util/SelectionManager"; -import { SketchPicker } from "react-color"; import { ScriptField } from "../fields/ScriptField"; import InkOptionsMenu from "../client/views/collections/collectionFreeForm/InkOptionsMenu"; -import { RadialMenu } from "../client/views/nodes/RadialMenu"; library.add(faTasks, faMobile, faThLarge, faWindowClose, faEdit, faTrashAlt, faPalette, faAngleRight, faBell, faTrash, faCamera, faExpand, faCaretDown, faCaretLeft, faCaretRight, faCaretSquareDown, faCaretSquareRight, faArrowsAltH, faPlus, faMinus, faTerminal, faToggleOn, fileSolid, faExternalLinkAlt, faLocationArrow, faSearch, faFileDownload, faStop, faCalculator, faWindowMaximize, faAddressCard, @@ -55,27 +50,17 @@ export class MobileInterface extends React.Component { @computed private get mainContainer() { return this.userDoc ? FieldValue(Cast(this.userDoc.activeMobile, Doc)) : CurrentUserUtils.GuestMobile; } @observable private mainDoc: any = CurrentUserUtils.setupActiveMobile(this.userDoc); @observable private renderView?: () => JSX.Element; - @observable private audioState: any; - @observable private activeToolbar: boolean = false; @observable private sidebarActive: boolean = false; @observable private imageUploadActive: boolean = false; @observable private menuListView: boolean = false; + @observable private _ink: boolean = false; public _activeDoc: Doc = this.mainDoc; public _homeDoc: Doc = this.mainDoc; private _homeMenu: boolean = true; - - // private inkDoc?: Doc; - public drawingInk: boolean = false; - - // private _uploadDoc: Doc = this.userDoc; private _child: Doc | null = null; private _parents: Array<Doc> = []; private _library: Doc = CurrentUserUtils.setupLibrary(this.userDoc); - private _open: boolean = false; - - // private _library: Doc = Cast(this.userDoc.myWorkspaces, Doc) as Doc; - @observable private _ink: boolean = false; constructor(props: Readonly<{}>) { super(props); @@ -93,11 +78,12 @@ export class MobileInterface extends React.Component { document.addEventListener("dblclick", this.onReactDoubleClick); } + // Prevent zooming in when double tapping the screen onReactDoubleClick = (e: MouseEvent) => { - console.log("tapped"); e.stopPropagation(); } + // Switch the mobile view to the given doc @action switchCurrentView = (doc: (userDoc: Doc) => Doc, renderView?: () => JSX.Element, onSwitch?: () => void) => { if (!this.userDoc) return; @@ -133,11 +119,12 @@ export class MobileInterface extends React.Component { }); } + // For toggling the hamburger menu @action toggleSidebar = () => this.sidebarActive = !this.sidebarActive /** - * Method called when 'Library' button is pressed + * Method called when 'Library' button is pressed on the home screen */ switchToLibrary = () => { this._parents.push(this._activeDoc); @@ -148,11 +135,12 @@ export class MobileInterface extends React.Component { } /** - * Back method for navigating within library + * Back method for navigating */ back = () => { let header = document.getElementById("header") as HTMLElement; let doc = Cast(this._parents.pop(), Doc) as Doc; + if (doc === Cast(this._library, Doc) as Doc) { this._child = null; this.userDoc.activeMobile = this._library; @@ -196,17 +184,13 @@ export class MobileInterface extends React.Component { * Return to primary Workspace in library (Workspaces Doc) */ returnMain = () => { - console.log("home"); this._parents = [this._homeDoc]; - // this.toggleSidebar(); this._activeDoc = this._library; this.switchCurrentView((userDoc: Doc) => this._library); this._homeMenu = false; this._child = null; } - // @computed get onChildClickHandler() { return ScriptCast(Doc.UserDoc.onClick); } - /** * DocumentView for graphic display of all documents */ @@ -249,7 +233,8 @@ export class MobileInterface extends React.Component { returnHeight = () => (window.innerHeight - 300); //Calculating the windows height (-300 to account for topbar) /** - * Handles the click functionality in the library panel + * Handles the click functionality in the library panel. + * Navigates to the given doc and updates the sidebar. * @param doc: doc for which the method is called */ handleClick = async (doc: Doc) => { @@ -269,17 +254,12 @@ export class MobileInterface extends React.Component { this._homeMenu = false; this._child = doc; } - - // let sidebar = document.getElementById("sidebar") as HTMLElement; - // sidebar.classList.toggle('active'); } /** * Handles creation of array which is then rendered in renderPathbar() */ createPathname = () => { - // let pathname = 'workspaces'; - // let titleArray = []; let docArray = []; this._parents.map((doc: Doc, index: any) => { docArray.push(doc); @@ -290,7 +270,6 @@ export class MobileInterface extends React.Component { // Renders the graphical pathbar renderPathbar = () => { - // if (this._homeMenu == false) { let docArray = this.createPathname(); let items = docArray.map((doc: Doc, index: any) => { if (index === 0) { @@ -355,7 +334,7 @@ export class MobileInterface extends React.Component { } } - // Handles when user clicks on document in the pathbar + // Handles when user clicks on a document in the pathbar handlePathClick = (doc: Doc, index: number) => { if (doc === this._library) { this._activeDoc = doc; @@ -372,8 +351,8 @@ export class MobileInterface extends React.Component { } } + // Renders the contents of the menu and sidebar renderDefaultContent = () => { - if (this._homeMenu === true) { return ( <div> @@ -457,6 +436,7 @@ export class MobileInterface extends React.Component { e.stopPropagation(); } + // Button for uploading mobile audio uploadAudioButton = () => { if (this._activeDoc.type === "audio") { return <div className="docButton" @@ -470,62 +450,23 @@ export class MobileInterface extends React.Component { } } - - @action - toggleSelector = () => this.activeToolbar = !this.activeToolbar - - - colorTool = () => { - if (this._activeDoc._viewType === "docking") { - // const color = InkingControl.Instance.selectedColor; - const color = "lightpink"; - const selDoc = SelectionManager.SelectedDocuments()?.[0]?.rootDoc; - return ( - <div - className="docButton" - style={{ backgroundColor: color }} - onClick={this.toggleSelector} - > - <div className={`toolbar ${this.activeToolbar ? "active" : ""}`}> - <div className="colorSelector"> - {/* <SketchPicker onChange={InkingControl.Instance.switchColor} presetColors={['#D0021B', '#F5A623', '#F8E71C', '#8B572A', '#7ED321', '#417505', '#9013FE', '#4A90E2', '#50E3C2', '#B8E986', '#000000', '#4A4A4A', '#9B9B9B', '#FFFFFF', '#f1efeb', 'transparent']} - color={StrCast(CurrentUserUtils.ActivePen ? CurrentUserUtils.ActivePen.backgroundColor : undefined, - StrCast(selDoc?._backgroundColor, StrCast(selDoc?.backgroundColor, "black")))} /> */} - <InkOptionsMenu /> - </div> - - <div className="widthSelector"> - {/* <input type="range" min="1" max="100" defaultValue="2" id="myRange" onChange={(e: React.ChangeEvent<HTMLInputElement>) => InkingControl.Instance.switchWidth(e.target.value)} /> */} - </div> - </div> - </div> - ); - } - } - + // Button for switching between pan and ink mode @action onSwitchInking = () => { const button = document.getElementById("inkButton") as HTMLElement; - // const color = InkingControl.Instance.selectedColor; - const color = "lightpink"; button.style.backgroundColor = this._ink ? "white" : "black"; button.style.color = this._ink ? "black" : "white"; if (!this._ink) { - console.log("INK IS ACTIVE"); - // InkingControl.Instance.switchTool(InkTool.Pen); Doc.SetSelectedTool(InkTool.Pen); - //InkOptionsMenu.Instance.jumpTo(300, 300); this._ink = true; } else { - console.log("INK IS INACTIVE"); - // InkingControl.Instance.switchTool(InkTool.None); Doc.SetSelectedTool(InkTool.None); - //InkOptionsMenu.Instance.fadeOut(true); this._ink = false; } } + // The static ink menu that appears at the top inkMenu = () => { if (this._activeDoc._viewType === "docking") { if (this._ink) { @@ -538,9 +479,9 @@ export class MobileInterface extends React.Component { } } + // Button for switching into ink mode drawInk = () => { if (this._activeDoc._viewType === "docking") { - const inkIsOn = this._ink; return ( <> <div className="docButton" @@ -550,15 +491,11 @@ export class MobileInterface extends React.Component { <FontAwesomeIcon className="documentdecorations-icon" size="sm" icon="pen-nib" /> </div> - {/* <div className={`colorMenu ${this._ink ? "active" : ""}`}> - <InkOptionsMenu /> - </div> */} - : - </>); } } + // Button to download images on the mobile downloadDocument = () => { if (this._activeDoc.type === "image") { const url = this._activeDoc["data-path"]?.toString(); @@ -575,6 +512,7 @@ export class MobileInterface extends React.Component { } } + // Mobile audio doc recordAudio = async () => { // upload to server with known URL if (this._activeDoc.title !== "mobile audio") { @@ -585,35 +523,24 @@ export class MobileInterface extends React.Component { this._activeDoc = audioDoc; this.switchCurrentView((userDoc: Doc) => audioDoc); this._homeMenu = false; - // this.toggleSidebar(); } - // const audioRightSidebar = Cast(Doc.UserDoc().rightSidebarCollection, Doc) as Doc; - // this.audioState = await audioDoc.getProto; - // if (this.audioState) { - // console.log(this.audioState); - // const data = Cast(audioRightSidebar.data, listSpec(Doc)); - // if (data) { - // data.push(audioDoc); - // } - // } } + // Pushing the audio doc onto Dash Web through the right side bar uploadAudio = () => { const audioRightSidebar = Cast(Doc.UserDoc().rightSidebarCollection, Doc) as Doc; const audioDoc = this._activeDoc; const data = Cast(audioRightSidebar.data, listSpec(Doc)); + if (data) { data.push(audioDoc); } - // this.recordAudio(); } panelHeight = () => window.innerHeight; panelWidth = () => window.innerWidth; - //WAS 3 - - //WAS 1 + // Button for pinning images to presentation pinToPresentation = () => { // Only making button available if it is an image if (this._activeDoc.type === "image") { @@ -635,6 +562,7 @@ export class MobileInterface extends React.Component { } } + // Buttons for switching the menu between large and small icons switchMenuView = () => { if (this._activeDoc.title === this._homeDoc.title) { return ( @@ -650,6 +578,7 @@ export class MobileInterface extends React.Component { } } + // Logics for switching the menu into the icons @action changeToIconView = () => { if (this._homeDoc._viewType = "stacking") { @@ -673,6 +602,7 @@ export class MobileInterface extends React.Component { } } + // Logics for switching the menu into the stacking view @action changeToListView = () => { if (this._homeDoc._viewType = "masonry") { @@ -692,6 +622,7 @@ export class MobileInterface extends React.Component { } } + // For setting up the presentation document for the home menu setupDefaultPresentation = () => { if (this._activeDoc.title !== "Presentation") { this._parents.push(this._activeDoc); @@ -700,33 +631,48 @@ export class MobileInterface extends React.Component { const presentation = Cast(Doc.UserDoc().activePresentation, Doc) as Doc; if (presentation) { - console.log("presentation clicked: " + presentation.title); this._activeDoc = presentation; this.switchCurrentView((userDoc: Doc) => presentation); this._homeMenu = false; - // this.toggleSidebar(); } } + // For toggling image upload pop up + @action + toggleUpload = () => this.imageUploadActive = !this.imageUploadActive + + // For closing the image upload pop up + @action + closeUpload = () => { + this.imageUploadActive = false; + } + + // Returns the image upload pop up + uploadImage = () => { + if (this.imageUploadActive) { + console.log("active"); + } else if (!this.imageUploadActive) { + + } + return ( + <div> + <div className="closeUpload" onClick={this.toggleUpload}> + <FontAwesomeIcon icon="window-close" size={"lg"} /> + </div> + <Uploader /> + </div> + ); + } + 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 : <></>;onDragOver={this.onDragOver} return ( <div className="mobileInterface-container" onDragOver={this.onDragOver}> - {/* <DocumentDecorations /> - <GestureOverlay> - {this.renderView ? this.renderView() : this.renderDefaultContent()} - </GestureOverlay> */} - {/* <GestureOverlay> */} <SettingsManager /> - {/* {this.menuOptions()} */} - {/* {this.displayHome()} */} <div className={`image-upload ${this.imageUploadActive ? "active" : ""}`}> {this.uploadImage()} </div> @@ -736,53 +682,12 @@ export class MobileInterface extends React.Component { {this.downloadDocument()} {this.drawInk()} {this.uploadAudioButton()} - {/* {this.colorTool()} */} </div> {this.inkMenu()} <GestureOverlay> {this.displayWorkspaces()} {this.renderDefaultContent()} </GestureOverlay> - {/* </GestureOverlay> */} - {/* <DictationOverlay /> - <SharingManager /> - <GoogleAuthenticationManager /> */} - {/* <DocumentDecorations /> */} - {/* <div> - {this.renderDefaultContent()} - </div> */} - {/* <PreviewCursor /> */} - {/* <ContextMenu /> */} - {/* <RadialMenu /> - <RichTextMenu /> */} - {/* <PDFMenu /> - <MarqueeOptionsMenu /> - <OverlayView /> */} - </div> - ); - } - - @action - toggleUpload = () => this.imageUploadActive = !this.imageUploadActive - - - @action - closeUpload = () => { - this.imageUploadActive = false; - } - - uploadImage = () => { - if (this.imageUploadActive) { - console.log("active"); - } else if (!this.imageUploadActive) { - - } - return ( - <div> - <div className="closeUpload" onClick={this.toggleUpload}> - <FontAwesomeIcon icon="window-close" size={"lg"} /> - </div> - <Uploader /> </div> ); } @@ -795,97 +700,3 @@ Scripting.addGlobal(function openMobileAudio() { return MobileInterface.Instance Scripting.addGlobal(function openMobileSettings() { return SettingsManager.Instance.open(); }); Scripting.addGlobal(function switchToLibrary() { return MobileInterface.Instance.switchToLibrary(); }); Scripting.addGlobal(function uploadImageMobile() { return MobileInterface.Instance.toggleUpload(); }); - - - -// WAS 2 - -// 1 -// renderUploadContent() { -// if (this.mainContainer) { -// return ( -// <div className="mobileInterface" onDragOver={this.onDragOver}> -// <div className="mobileInterface-inkInterfaceButtons"> -// <button className="mobileInterface-button cancel" onClick={this.onBack} title="Back">BACK</button> -// {/* <button className="mobileInterface-button" onClick={this.clearUpload} title="Clear Upload">CLEAR</button> */} -// {/* <button className="mobileInterface-button" onClick={this.addWeb} title="Add Web Doc to Upload Collection"></button> */} -// <button className="mobileInterface-button" onClick={this.upload} title="Upload">UPLOAD</button> -// </div> -// <DocumentView -// Document={this.mainContainer} -// DataDoc={undefined} -// LibraryPath={emptyPath} -// addDocument={returnFalse} -// addDocTab={returnFalse} -// pinToPres={emptyFunction} -// rootSelected={returnFalse} -// removeDocument={undefined} -// onClick={undefined} -// ScreenToLocalTransform={Transform.Identity} -// ContentScaling={returnOne} -// NativeHeight={returnZero} -// NativeWidth={returnZero} -// PanelWidth={() => window.screen.width} -// PanelHeight={() => window.screen.height} -// renderDepth={0} -// focus={emptyFunction} -// backgroundColor={returnEmptyString} -// parentActive={returnTrue} -// whenActiveChanged={emptyFunction} -// bringToFront={emptyFunction} -// ContainingCollectionView={undefined} -// ContainingCollectionDoc={undefined} /> -// </div> -// ); -// } -// } - -// 3 - // renderInkingContent = () => { - // console.log("rendering inking content"); - // // TODO: support panning and zooming - // // TODO: handle moving of ink strokes - // if (this.mainContainer) { - // return ( - // <div className="mobileInterface"> - // <div className="mobileInterface-inkInterfaceButtons"> - // <div className="navButtons"> - // <button className="mobileInterface-button cancel" onClick={this.onBack} title="Cancel drawing">BACK</button> - // </div> - // <div className="inkSettingButtons"> - // <button className="mobileInterface-button cancel" onClick={this.onBack} title="Cancel drawing"><FontAwesomeIcon icon="long-arrow-alt-left" /></button> - // </div> - // <div className="navButtons"> - // <button className="mobileInterface-button" onClick={this.shiftLeft} title="Shift left">left</button> - // <button className="mobileInterface-button" onClick={this.shiftRight} title="Shift right">right</button> - // </div> - // </div> - // <CollectionView - // Document={this.mainContainer} - // DataDoc={undefined} - // LibraryPath={emptyPath} - // fieldKey={""} - // dropAction={"alias"} - // bringToFront={emptyFunction} - // addDocTab={returnFalse} - // pinToPres={emptyFunction} - // PanelWidth={this.panelWidth} - // PanelHeight={this.panelHeight} - // NativeHeight={returnZero} - // NativeWidth={returnZero} - // focus={emptyFunction} - // isSelected={returnFalse} - // select={emptyFunction} - // active={returnFalse} - // ContentScaling={returnOne} - // whenActiveChanged={returnFalse} - // ScreenToLocalTransform={Transform.Identity} - // renderDepth={0} - // ContainingCollectionView={undefined} - // ContainingCollectionDoc={undefined} - // rootSelected={returnTrue}> - // </CollectionView> - // </div> - // ); - // } - // } |