diff options
author | usodhi <61431818+usodhi@users.noreply.github.com> | 2020-07-06 15:33:45 +0530 |
---|---|---|
committer | usodhi <61431818+usodhi@users.noreply.github.com> | 2020-07-06 15:33:45 +0530 |
commit | b442fc347abc267697575c517949ca0ee0dad2f1 (patch) | |
tree | fe5e0aca9dbf155196b0e8514cdcadbfc26dc36d /src | |
parent | 94137cb3a771ec6afd803f3cff97da86a14dd54f (diff) | |
parent | 6b24899bcf2c099163c1ca872d65b6318c11a53b (diff) |
Merge branch 'master' of https://github.com/browngraphicslab/Dash-Web into grid_view_secondary
Diffstat (limited to 'src')
138 files changed, 8181 insertions, 2651 deletions
diff --git a/src/Utils.ts b/src/Utils.ts index dba802f98..a01a94134 100644 --- a/src/Utils.ts +++ b/src/Utils.ts @@ -7,6 +7,22 @@ import { ColorState } from 'react-color'; export namespace Utils { export let DRAG_THRESHOLD = 4; + export function readUploadedFileAsText(inputFile: File) { + const temporaryFileReader = new FileReader(); + + return new Promise((resolve, reject) => { + temporaryFileReader.onerror = () => { + temporaryFileReader.abort(); + reject(new DOMException("Problem parsing input file.")); + }; + + temporaryFileReader.onload = () => { + resolve(temporaryFileReader.result); + }; + temporaryFileReader.readAsText(inputFile); + }); + } + export function GenerateGuid(): string { return v4(); } diff --git a/src/client/DocServer.ts b/src/client/DocServer.ts index c7dfb0b23..2a7a7c59a 100644 --- a/src/client/DocServer.ts +++ b/src/client/DocServer.ts @@ -31,16 +31,19 @@ export namespace DocServer { export enum WriteMode { Default = 0, //Anything goes - Playground = 1, - LiveReadonly = 2, - LivePlayground = 3, + Playground = 1, //Playground (write own/no read) + LiveReadonly = 2,//Live Readonly (no write/read others) + LivePlayground = 3,//Live Playground (write own/read others) } - - export let AclsMode = WriteMode.Default; - const fieldWriteModes: { [field: string]: WriteMode } = {}; const docsWithUpdates: { [field: string]: Set<Doc> } = {}; + export var PlaygroundFields: string[]; + export function setPlaygroundFields(livePlayougroundFields: string[]) { + DocServer.PlaygroundFields = livePlayougroundFields; + livePlayougroundFields.forEach(f => DocServer.setFieldWriteMode(f, DocServer.WriteMode.LivePlayground)); + } + export function setFieldWriteMode(field: string, writeMode: WriteMode) { fieldWriteModes[field] = writeMode; if (writeMode !== WriteMode.Playground) { diff --git a/src/client/apis/google_docs/GooglePhotosClientUtils.ts b/src/client/apis/google_docs/GooglePhotosClientUtils.ts index a604c7de1..13bfb3a91 100644 --- a/src/client/apis/google_docs/GooglePhotosClientUtils.ts +++ b/src/client/apis/google_docs/GooglePhotosClientUtils.ts @@ -130,7 +130,6 @@ export namespace GooglePhotos { const uploads = await Transactions.WriteMediaItemsToServer(response); const children = uploads.map((upload: Transactions.UploadInformation) => { const document = Docs.Create.ImageDocument(Utils.fileUrl(upload.fileNames.clean)); - document.fillColumn = true; document.contentSize = upload.contentSize; return document; }); diff --git a/src/client/documents/DocumentTypes.ts b/src/client/documents/DocumentTypes.ts index 7ba21b2f6..7578b7df0 100644 --- a/src/client/documents/DocumentTypes.ts +++ b/src/client/documents/DocumentTypes.ts @@ -32,8 +32,10 @@ export enum DocumentType { YOUTUBE = "youtube", // youtube directory (view of you tube search results) DOCHOLDER = "docholder", // nested document (view of a document) COMPARISON = "comparison", // before/after view with slider (view of 2 images) + GROUP = "group", // group of users LINKDB = "linkdb", // database of links ??? why do we have this SCRIPTDB = "scriptdb", // database of scripts RECOMMENDATION = "recommendation", // view of a recommendation + GROUPDB = "groupdb" // database of groups }
\ No newline at end of file diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 6c2c6faea..f81c25bab 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -1,5 +1,5 @@ -import { runInAction } from "mobx"; -import { extname } from "path"; +import { runInAction, action } from "mobx"; +import { extname, basename } from "path"; import { DateField } from "../../fields/DateField"; import { Doc, DocListCast, DocListCastAsync, Field, HeightSym, Opt, WidthSym } from "../../fields/Doc"; import { HtmlField } from "../../fields/HtmlField"; @@ -13,17 +13,19 @@ import { Cast, NumCast, StrCast } from "../../fields/Types"; import { AudioField, ImageField, PdfField, VideoField, WebField, YoutubeField } from "../../fields/URLField"; import { MessageStore } from "../../server/Message"; import { OmitKeys, Utils } from "../../Utils"; +import { YoutubeBox } from "../apis/youtube/YoutubeBox"; import { DocServer } from "../DocServer"; +import { DocumentManager } from "../util/DocumentManager"; import { dropActionType } from "../util/DragManager"; +import { DirectoryImportBox } from "../util/Import & Export/DirectoryImportBox"; import { LinkManager } from "../util/LinkManager"; import { Scripting } from "../util/Scripting"; import { UndoManager } from "../util/UndoManager"; -import { DocumentType } from "./DocumentTypes"; import { CollectionDockingView } from "../views/collections/CollectionDockingView"; import { CollectionView, CollectionViewType } from "../views/collections/CollectionView"; import { ContextMenu } from "../views/ContextMenu"; import { ContextMenuProps } from "../views/ContextMenuItem"; -import { ActiveInkBezierApprox, ActiveInkColor, ActiveInkWidth, InkingStroke } from "../views/InkingStroke"; +import { ActiveArrowEnd, ActiveArrowStart, ActiveDash, ActiveFillColor, ActiveInkBezierApprox, ActiveInkColor, ActiveInkWidth, InkingStroke } from "../views/InkingStroke"; import { AudioBox } from "../views/nodes/AudioBox"; import { ColorBox } from "../views/nodes/ColorBox"; import { ComparisonBox } from "../views/nodes/ComparisonBox"; @@ -45,9 +47,9 @@ import { WebBox } from "../views/nodes/WebBox"; import { PresElementBox } from "../views/presentationview/PresElementBox"; import { RecommendationsBox } from "../views/RecommendationsBox"; import { DashWebRTCVideo } from "../views/webcam/DashWebRTCVideo"; -import { YoutubeBox } from "../apis/youtube/YoutubeBox"; -import { DocumentManager } from "../util/DocumentManager"; -import { DirectoryImportBox } from "../util/Import & Export/DirectoryImportBox"; +import { DocumentType } from "./DocumentTypes"; +import { Networking } from "../Network"; +import { Upload } from "../../server/SharedMediaTypes"; const path = require('path'); export interface DocumentOptions { @@ -62,7 +64,7 @@ export interface DocumentOptions { _dimUnit?: string; // "px" or "*" (default = "*") _fitWidth?: boolean; _fitToBox?: boolean; // whether a freeformview should zoom/scale to create a shrinkwrapped view of its contents - _LODdisable?: boolean; + _freeformLOD?: boolean; // whether to use LOD to render a freeform document _showTitleHover?: string; // _showTitle?: string; // which field to display in the title area. leave empty to have no title _showCaption?: string; // which field to display in the caption area. leave empty to have no caption @@ -92,14 +94,14 @@ export interface DocumentOptions { label?: string; // short form of title for use as an icon label style?: string; page?: number; - scale?: number; + _viewScale?: number; isDisplayPanel?: boolean; // whether the panel functions as GoldenLayout "stack" used to display documents forceActive?: boolean; layout?: string | Doc; // default layout string for a document childLayoutTemplate?: Doc; // template for collection to use to render its children (see PresBox or Buxton layout in tree view) childLayoutString?: string; // template string for collection to use to render its children hideFilterView?: boolean; // whether to hide the filter popout on collections - hideHeadings?: boolean; // whether stacking view column headings should be hidden + _columnsHideIfEmpty?: boolean; // whether stacking view column headings should be hidden isTemplateForField?: string; // the field key for which the containing document is a rendering template isTemplateDoc?: boolean; targetScriptKey?: string; // where to write a template script (used by collections with click templates which need to target onClick, onDoubleClick, etc) @@ -119,7 +121,7 @@ export interface DocumentOptions { defaultBackgroundColor?: string; isBackground?: boolean; isLinkButton?: boolean; - columnWidth?: number; + _columnWidth?: number; _fontSize?: number; _fontFamily?: string; curPage?: number; @@ -137,7 +139,8 @@ export interface DocumentOptions { "onCheckedClick-rawScript"?: string; // onChecked script in raw text form "onCheckedClick-params"?: List<string>; // parameter list for onChecked treeview functions _pivotField?: string; // field key used to determine headings for sections in stacking, masonry, pivot views - schemaColumns?: List<SchemaHeaderField>; + _columnHeaders?: List<SchemaHeaderField>; // headers for stacking views + _schemaHeaders?: List<SchemaHeaderField>; // headers for schema view dockingConfig?: string; annotationOn?: Doc; removeDropProperties?: List<string>; // list of properties that should be removed from a document when it is dropped. e.g., a creator button may be forceActive to allow it be dragged, but the forceActive property can be removed from the dropped document @@ -168,6 +171,7 @@ export interface DocumentOptions { treeViewOpen?: boolean; // whether this document is expanded in a tree view treeViewExpandedView?: string; // which field/thing is displayed when this item is opened in tree view treeViewChecked?: ScriptField; // script to call when a tree view checkbox is checked + treeViewTruncateTitleWidth?: number; limitHeight?: number; // maximum height for newly created (eg, from pasting) text documents // [key: string]: Opt<Field>; pointerHack?: boolean; // for buttons, allows onClick handler to fire onPointerDown @@ -227,7 +231,7 @@ export namespace Docs { }], [DocumentType.COL, { layout: { view: CollectionView, dataField: defaultDataKey }, - options: { _panX: 0, _panY: 0, scale: 1 } // , _width: 500, _height: 500 } + options: { _panX: 0, _panY: 0, _viewScale: 1 } // , _width: 500, _height: 500 } }], [DocumentType.KVP, { layout: { view: KeyValueBox, dataField: defaultDataKey }, @@ -310,6 +314,14 @@ export namespace Docs { [DocumentType.COMPARISON, { layout: { view: ComparisonBox, dataField: defaultDataKey }, }], + [DocumentType.GROUPDB, { + data: new List<Doc>(), + layout: { view: EmptyBox, dataField: defaultDataKey }, + options: { childDropAction: "alias", title: "Global Group Database" } + }], + [DocumentType.GROUP, { + layout: { view: EmptyBox, dataField: defaultDataKey } + }] ]); // All document prototypes are initialized with at least these values @@ -373,6 +385,13 @@ export namespace Docs { } /** + * A collection of all groups in the database + */ + export function MainGroupDocument() { + return Prototypes.get(DocumentType.GROUPDB); + } + + /** * This is a convenience method that is used to initialize * prototype documents for the first time. * @@ -397,7 +416,7 @@ export namespace Docs { // synthesize the default options, the type and title from computed values and // whatever options pertain to this specific prototype const options = { title, type, baseProto: true, ...defaultOptions, ...(template.options || {}) }; - options.layout = layout.view.LayoutString(layout.dataField); + options.layout = layout.view?.LayoutString(layout.dataField); const doc = Doc.assign(new Doc(prototypeId, true), { layoutKey: "layout", ...options }); doc.layout_keyValue = KeyValueBox.LayoutString(""); return doc; @@ -427,8 +446,7 @@ export namespace Docs { const parent = TreeDocument([loading], { title: "The Buxton Collection", _width: 400, - _height: 400, - _LODdisable: true + _height: 400 }); const parentProto = Doc.GetProto(parent); const { _socket } = DocServer; @@ -464,7 +482,7 @@ export namespace Docs { return imageDoc; }); // the main document we create - const doc = StackingDocument(deviceImages, { title, _LODdisable: true, hero: new ImageField(constructed[0].url) }); + const doc = StackingDocument(deviceImages, { title, hero: new ImageField(constructed[0].url) }); doc.nameAliases = new List<string>([title.toLowerCase()]); // add the parsed attributes to this main document Doc.Get.FromJson({ data: device, appendToExisting: { targetDoc: Doc.GetProto(doc) } }); @@ -526,6 +544,8 @@ export namespace Docs { const dataDoc = MakeDataDelegate(proto, protoProps, data, fieldKey); const viewDoc = Doc.MakeDelegate(dataDoc, delegId); + proto.links = ComputedField.MakeFunction("links(self)"); + viewDoc.author = Doc.CurrentUserEmail; viewDoc.type !== DocumentType.LINK && DocUtils.MakeLinkToActiveAudio(viewDoc); @@ -645,13 +665,17 @@ export namespace Docs { return doc; } - export function InkDocument(color: string, tool: string, strokeWidth: string, strokeBezier: string, points: { X: number, Y: number }[], options: DocumentOptions = {}) { + export function InkDocument(color: string, tool: string, strokeWidth: string, strokeBezier: string, fillColor: string, arrowStart: string, arrowEnd: string, dash: string, points: { X: number, Y: number }[], options: DocumentOptions = {}) { const I = new Doc(); I.type = DocumentType.INK; I.layout = InkingStroke.LayoutString("data"); I.color = color; I.strokeWidth = strokeWidth; I.strokeBezier = strokeBezier; + I.fillColor = fillColor; + I.arrowStart = arrowStart; + I.arrowEnd = arrowEnd; + I.dash = dash; I.tool = tool; I.title = "ink"; I.x = options.x; @@ -691,15 +715,15 @@ export namespace Docs { } export function FreeformDocument(documents: Array<Doc>, options: DocumentOptions, id?: string) { - return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", schemaColumns: new List([new SchemaHeaderField("title", "#f1efeb")]), ...options, _viewType: CollectionViewType.Freeform }, id); + return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", ...options, _viewType: CollectionViewType.Freeform }, id); } export function PileDocument(documents: Array<Doc>, options: DocumentOptions, id?: string) { - return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", backgroundColor: "black", schemaColumns: new List([new SchemaHeaderField("title", "#f1efeb")]), ...options, _viewType: CollectionViewType.Pile }, id); + return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", backgroundColor: "black", ...options, _viewType: CollectionViewType.Pile }, id); } export function LinearDocument(documents: Array<Doc>, options: DocumentOptions, id?: string) { - return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", backgroundColor: "black", schemaColumns: new List([new SchemaHeaderField("title", "#f1efeb")]), ...options, _viewType: CollectionViewType.Linear }, id); + return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", backgroundColor: "black", ...options, _viewType: CollectionViewType.Linear }, id); } export function MapDocument(documents: Array<Doc>, options: DocumentOptions = {}) { @@ -707,31 +731,35 @@ export namespace Docs { } export function CarouselDocument(documents: Array<Doc>, options: DocumentOptions) { - return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", schemaColumns: new List([new SchemaHeaderField("title", "#f1efeb")]), ...options, _viewType: CollectionViewType.Carousel }); + return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", ...options, _viewType: CollectionViewType.Carousel }); } - 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.length ? schemaColumns : [new SchemaHeaderField("title", "#f1efeb")]), ...options, _viewType: CollectionViewType.Schema }); + export function Carousel3DDocument(documents: Array<Doc>, options: DocumentOptions) { + return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", ...options, _viewType: CollectionViewType.Carousel3D }); + } + + export function SchemaDocument(schemaHeaders: SchemaHeaderField[], documents: Array<Doc>, options: DocumentOptions) { + return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", _schemaHeaders: schemaHeaders.length ? new List(schemaHeaders) : undefined, ...options, _viewType: CollectionViewType.Schema }); } export function TreeDocument(documents: Array<Doc>, options: DocumentOptions, id?: string) { - return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", schemaColumns: new List([new SchemaHeaderField("title", "#f1efeb")]), ...options, _viewType: CollectionViewType.Tree }, id); + return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", ...options, _viewType: CollectionViewType.Tree }, id); } export function StackingDocument(documents: Array<Doc>, options: DocumentOptions, id?: string) { - return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", schemaColumns: new List([new SchemaHeaderField("title", "#f1efeb")]), ...options, _viewType: CollectionViewType.Stacking }, id); + return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", ...options, _viewType: CollectionViewType.Stacking }, id); } export function MulticolumnDocument(documents: Array<Doc>, options: DocumentOptions) { - return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", schemaColumns: new List([new SchemaHeaderField("title", "#f1efeb")]), ...options, _viewType: CollectionViewType.Multicolumn }); + return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", ...options, _viewType: CollectionViewType.Multicolumn }); } export function MultirowDocument(documents: Array<Doc>, options: DocumentOptions) { - return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", schemaColumns: new List([new SchemaHeaderField("title", "#f1efeb")]), ...options, _viewType: CollectionViewType.Multirow }); + return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", ...options, _viewType: CollectionViewType.Multirow }); } export function MasonryDocument(documents: Array<Doc>, options: DocumentOptions) { - return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", schemaColumns: new List([new SchemaHeaderField("title", "#f1efeb")]), ...options, _viewType: CollectionViewType.Masonry }); + return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", ...options, _viewType: CollectionViewType.Masonry }); } export function LabelDocument(options?: DocumentOptions) { @@ -838,6 +866,7 @@ export namespace DocUtils { export function MakeLinkToActiveAudio(doc: Doc) { DocUtils.ActiveRecordings.map(d => DocUtils.MakeLink({ doc: doc }, { doc: d }, "audio link", "audio timeline")); } + export function MakeLink(source: { doc: Doc }, target: { doc: Doc }, linkRelationship: string = "", id?: string) { const sv = DocumentManager.Instance.getDocumentView(source.doc); if (sv && sv.props.ContainingCollectionDoc === target.doc) return; @@ -849,6 +878,7 @@ export namespace DocUtils { Doc.GetProto(source.doc).links = ComputedField.MakeFunction("links(self)"); Doc.GetProto(target.doc).links = ComputedField.MakeFunction("links(self)"); + return linkDoc; } @@ -873,7 +903,7 @@ export namespace DocUtils { created = Docs.Create.AudioDocument((field).url.href, resolved); layout = AudioBox.LayoutString; } else if (field instanceof InkField) { - created = Docs.Create.InkDocument(ActiveInkColor(), Doc.GetSelectedTool(), ActiveInkWidth(), ActiveInkBezierApprox(), (field).inkData, resolved); + created = Docs.Create.InkDocument(ActiveInkColor(), Doc.GetSelectedTool(), ActiveInkWidth(), ActiveInkBezierApprox(), ActiveFillColor(), ActiveArrowStart(), ActiveArrowEnd(), ActiveDash(), (field).inkData, resolved); layout = InkingStroke.LayoutString; } else if (field instanceof List && field[0] instanceof Doc) { created = Docs.Create.StackingDocument(DocListCast(field), resolved); @@ -951,7 +981,7 @@ export namespace DocUtils { }); ContextMenu.Instance.addItem({ description: "Add Template Doc ...", - subitems: DocListCast(Cast(Doc.UserDoc().dockedBtns, Doc, null)?.data).map(btnDoc => Cast(btnDoc?.dragFactory, Doc, null)).filter(doc => doc).map((dragDoc, i) => ({ + subitems: DocListCast(Cast(Doc.UserDoc().myItemCreators, Doc, null)?.data).map(btnDoc => Cast(btnDoc?.dragFactory, Doc, null)).filter(doc => doc).map((dragDoc, i) => ({ description: ":" + StrCast(dragDoc.title), event: (args: { x: number, y: number }) => { const newDoc = Doc.ApplyTemplate(dragDoc); @@ -1043,7 +1073,7 @@ export namespace DocUtils { }); }); if (x !== undefined && y !== undefined) { - const newCollection = Docs.Create.PileDocument(docList, { title: "pileup", x: x - 55, y: y - 55, _width: 110, _height: 100, _LODdisable: true }); + const newCollection = Docs.Create.PileDocument(docList, { title: "pileup", x: x - 55, y: y - 55, _width: 110, _height: 100 }); newCollection.x = NumCast(newCollection.x) + NumCast(newCollection._width) / 2 - 55; newCollection.y = NumCast(newCollection.y) + NumCast(newCollection._height) / 2 - 55; newCollection._width = newCollection._height = 110; @@ -1078,6 +1108,32 @@ export namespace DocUtils { }); return optionsCollection; } + + export async function uploadFilesToDocs(files: File[], options: DocumentOptions) { + const generatedDocuments: Doc[] = []; + for (const { source: { name, type }, result } of await Networking.UploadFilesToServer(files)) { + if (result instanceof Error) { + alert(`Upload failed: ${result.message}`); + return []; + } + const full = { ...options, _width: 400, title: name }; + const pathname = Utils.prepend(result.accessPaths.agnostic.client); + const doc = await DocUtils.DocumentFromType(type, pathname, full); + if (!doc) { + continue; + } + const proto = Doc.GetProto(doc); + proto.text = result.rawText; + proto.fileUpload = basename(pathname).replace("upload_", "").replace(/\.[a-z0-9]*$/, ""); + if (Upload.isImageInformation(result)) { + proto["data-nativeWidth"] = (result.nativeWidth > result.nativeHeight) ? 400 * result.nativeWidth / result.nativeHeight : 400; + proto["data-nativeHeight"] = (result.nativeWidth > result.nativeHeight) ? 400 : 400 / (result.nativeWidth / result.nativeHeight); + proto.contentSize = result.contentSize; + } + generatedDocuments.push(doc); + } + return generatedDocuments; + } } Scripting.addGlobal("Docs", Docs); diff --git a/src/client/util/CurrentUserUtils.ts b/src/client/util/CurrentUserUtils.ts index 76c1fc9f7..4276e04e4 100644 --- a/src/client/util/CurrentUserUtils.ts +++ b/src/client/util/CurrentUserUtils.ts @@ -43,7 +43,7 @@ export class CurrentUserUtils { const queryTemplate = Docs.Create.MulticolumnDocument( [ Docs.Create.QueryDocument({ title: "query", _height: 200 }), - Docs.Create.FreeformDocument([], { title: "data", _height: 100, _LODdisable: true }) + Docs.Create.FreeformDocument([], { title: "data", _height: 100 }) ], { _width: 400, _height: 300, title: "queryView", _chromeStatus: "disabled", _xMargin: 3, _yMargin: 3, hideFilterView: true } ); @@ -54,6 +54,25 @@ export class CurrentUserUtils { removeDropProperties: new List<string>(["dropAction"]), title: "query view", icon: "question-circle" }); } + // Prototype for mobile button (not sure if 'Advanced Item Prototypes' is ideal location) + if (doc["template-mobile-button"] === undefined) { + const queryTemplate = this.mobileButton({ + title: "NEW MOBILE BUTTON", + onClick: undefined, + }, + [this.ficon({ + ignoreClick: true, + icon: "mobile", + backgroundColor: "rgba(0,0,0,0)" + }), + this.mobileTextContainer({}, + [this.mobileButtonText({}, "NEW MOBILE BUTTON"), this.mobileButtonInfo({}, "You can customize this button and make it your own.")])]); + doc["template-mobile-button"] = CurrentUserUtils.ficon({ + onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), + dragFactory: new PrefetchProxy(queryTemplate) as any as Doc, + removeDropProperties: new List<string>(["dropAction"]), title: "mobile button", icon: "mobile" + }); + } if (doc["template-button-slides"] === undefined) { const slideTemplate = Docs.Create.MultirowDocument( @@ -136,9 +155,9 @@ export class CurrentUserUtils { if (doc["template-button-switch"] === undefined) { const { FreeformDocument, MulticolumnDocument, TextDocument } = Docs.Create; - const yes = FreeformDocument([], { title: "yes", _height: 35, _width: 50, _LODdisable: true, _dimUnit: DimUnit.Pixel, _dimMagnitude: 40 }); + const yes = FreeformDocument([], { title: "yes", _height: 35, _width: 50, _dimUnit: DimUnit.Pixel, _dimMagnitude: 40 }); const name = TextDocument("name", { title: "name", _height: 35, _width: 70, _dimMagnitude: 1 }); - const no = FreeformDocument([], { title: "no", _height: 100, _width: 100, _LODdisable: true }); + const no = FreeformDocument([], { title: "no", _height: 100, _width: 100 }); const labelTemplate = { doc: { type: "doc", content: [{ @@ -193,10 +212,10 @@ export class CurrentUserUtils { const shared = { _chromeStatus: "disabled", _autoHeight: true, _xMargin: 0 }; const detailViewOpts = { title: "detailView", _width: 300, _fontFamily: "Arial", _fontSize: 12 }; - const descriptionWrapperOpts = { title: "descriptions", _height: 300, columnWidth: -1, treeViewHideTitle: true, _pivotField: "title" }; + const descriptionWrapperOpts = { title: "descriptions", _height: 300, _columnWidth: -1, treeViewHideTitle: true, _pivotField: "title" }; const descriptionWrapper = MasonryDocument([details, short, long], { ...shared, ...descriptionWrapperOpts }); - descriptionWrapper.sectionHeaders = new List<SchemaHeaderField>([ + descriptionWrapper._columnHeaders = new List<SchemaHeaderField>([ new SchemaHeaderField("[A Short Description]", "dimGray", undefined, undefined, undefined, false), new SchemaHeaderField("[Long Description]", "dimGray", undefined, undefined, undefined, true), new SchemaHeaderField("[Details]", "dimGray", undefined, undefined, undefined, true), @@ -219,13 +238,14 @@ export class CurrentUserUtils { doc["template-button-slides"] as Doc, doc["template-button-description"] as Doc, doc["template-button-query"] as Doc, + doc["template-mobile-button"] 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(requiredTypes, { title: "Advanced Item Prototypes", _xMargin: 0, _showTitle: "title", - _autoHeight: true, _width: 500, columnWidth: 35, ignoreClick: true, lockedPosition: true, _chromeStatus: "disabled", + _autoHeight: true, _width: 500, _columnWidth: 35, ignoreClick: true, lockedPosition: true, _chromeStatus: "disabled", dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }), })); } else { @@ -306,21 +326,17 @@ export class CurrentUserUtils { // setup templates for different document types when they are iconified from Document Decorations static setupDefaultIconTemplates(doc: Doc) { if (doc["template-icon-view"] === undefined) { - const iconView = Docs.Create.TextDocument("", { - title: "icon", _width: 150, _height: 30, isTemplateDoc: true, onDoubleClick: ScriptField.MakeScript("deiconifyView(self)") + const iconView = Docs.Create.LabelDocument({ + title: "icon", textTransform: "unset", letterSpacing: "unset", layout: LabelBox.LayoutString("title"), _backgroundColor: "dimGray", + _width: 150, _height: 70, _xPadding: 10, _yPadding: 10, isTemplateDoc: true, onDoubleClick: ScriptField.MakeScript("deiconifyView(self)") }); - Doc.GetProto(iconView).icon = new RichTextField('{"doc":{"type":"doc","content":[{"type":"paragraph","attrs":{"align":null,"color":null,"id":null,"indent":null,"inset":null,"lineSpacing":null,"paddingBottom":null,"paddingTop":null},"content":[{"type":"dashField","attrs":{"fieldKey":"title","docid":""}}]}]},"selection":{"type":"text","anchor":2,"head":2},"storedMarks":[]}', ""); + // Docs.Create.TextDocument("", { + // title: "icon", _width: 150, _height: 30, isTemplateDoc: true, onDoubleClick: ScriptField.MakeScript("deiconifyView(self)") + // }); + // Doc.GetProto(iconView).icon = new RichTextField('{"doc":{"type":"doc","content":[{"type":"paragraph","attrs":{"align":null,"color":null,"id":null,"indent":null,"inset":null,"lineSpacing":null,"paddingBottom":null,"paddingTop":null},"content":[{"type":"dashField","attrs":{"fieldKey":"title","docid":""}}]}]},"selection":{"type":"text","anchor":2,"head":2},"storedMarks":[]}', ""); iconView.isTemplateDoc = makeTemplate(iconView); doc["template-icon-view"] = new PrefetchProxy(iconView); } - if (doc["template-icon-view-pdf"] === undefined) { - const iconPdfView = Docs.Create.LabelDocument({ - title: "icon_" + DocumentType.PDF, textTransform: "unset", letterSpacing: "unset", layout: LabelBox.LayoutString("title"), _backgroundColor: "dimGray", - _width: 150, _height: 70, _xPadding: 10, _yPadding: 10, isTemplateDoc: true, onDoubleClick: ScriptField.MakeScript("deiconifyView(self)") - }); - iconPdfView.isTemplateDoc = makeTemplate(iconPdfView, true, "icon_" + DocumentType.PDF); - doc["template-icon-view-pdf"] = new PrefetchProxy(iconPdfView); - } if (doc["template-icon-view-rtf"] === undefined) { const iconRtfView = Docs.Create.LabelDocument({ title: "icon_" + DocumentType.RTF, textTransform: "unset", letterSpacing: "unset", layout: LabelBox.LayoutString("text"), @@ -347,7 +363,7 @@ export class CurrentUserUtils { } else { const templateIconsDoc = Cast(doc["template-icons"], Doc, null); const requiredTypes = [doc["template-icon-view"] as Doc, doc["template-icon-view-img"] as Doc, - doc["template-icon-view-col"] as Doc, doc["template-icon-view-rtf"] as Doc, doc["template-icon-view-pdf"] as Doc]; + doc["template-icon-view-col"] as Doc, doc["template-icon-view-rtf"] as Doc]; DocListCastAsync(templateIconsDoc.data).then(async curIcons => { await Promise.all(curIcons!); requiredTypes.map(ntype => Doc.AddDocToList(templateIconsDoc, "data", ntype)); @@ -362,11 +378,17 @@ export class CurrentUserUtils { }[] { if (doc.emptyPresentation === undefined) { doc.emptyPresentation = Docs.Create.PresDocument(new List<Doc>(), - { title: "Presentation", _viewType: CollectionViewType.Stacking, targetDropAction: "alias", _LODdisable: true, _chromeStatus: "replaced", _showTitle: "title", boxShadow: "0 0" }); + { title: "Presentation", _viewType: CollectionViewType.Stacking, targetDropAction: "alias", _chromeStatus: "replaced", _showTitle: "title", boxShadow: "0 0" }); } if (doc.emptyCollection === undefined) { doc.emptyCollection = Docs.Create.FreeformDocument([], - { _nativeWidth: undefined, _nativeHeight: undefined, _LODdisable: true, _width: 150, _height: 100, title: "freeform" }); + { _nativeWidth: undefined, _nativeHeight: undefined, _width: 150, _height: 100, title: "freeform" }); + } + if (doc.emptyComparison === undefined) { + doc.emptyComparison = Docs.Create.ComparisonDocument({ title: "compare", _width: 300, _height: 300 }); + } + if (doc.emptyScript === undefined) { + doc.emptyScript = Docs.Create.ScriptingDocument(undefined, { _width: 200, _height: 250, title: "script" }); } if (doc.emptyDocHolder === undefined) { doc.emptyDocHolder = Docs.Create.DocumentDocument( @@ -374,10 +396,13 @@ export class CurrentUserUtils { { _width: 250, _height: 250, title: "container" }); } if (doc.emptyWebpage === undefined) { - doc.emptyWebpage = Docs.Create.WebDocument("", { title: "New Webpage", _nativeWidth: 850, _nativeHeight: 962, _width: 600, UseCors: true }); + doc.emptyWebpage = Docs.Create.WebDocument("", { title: "webpage", _nativeWidth: 850, _nativeHeight: 962, _width: 600, UseCors: true }); + } + if (doc.activeMobileMenu === undefined) { + this.setupActiveMobileMenu(doc); } return [ - { title: "Drag a comparison box", label: "Comp", icon: "columns", ignoreClick: true, drag: 'Docs.Create.ComparisonDocument()' }, + { title: "Drag a comparison box", label: "Comp", icon: "columns", click: 'openOnRight(getCopy(this.dragFactory, true))', drag: 'getCopy(this.dragFactory, true)', dragFactory: doc.emptyComparison as Doc }, { title: "Drag a collection", label: "Col", icon: "folder", click: 'openOnRight(getCopy(this.dragFactory, true))', drag: 'getCopy(this.dragFactory, true)', dragFactory: doc.emptyCollection as Doc }, { title: "Drag a web page", label: "Web", icon: "globe-asia", click: 'openOnRight(getCopy(this.dragFactory, true))', drag: 'getCopy(this.dragFactory, true)', dragFactory: doc.emptyWebpage as Doc }, { title: "Drag a cat image", label: "Img", icon: "cat", ignoreClick: true, drag: 'Docs.Create.ImageDocument("https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg", { _width: 250, _nativeWidth:250, title: "an image of a cat" })' }, @@ -387,9 +412,9 @@ export class CurrentUserUtils { { title: "Drag a clickable button", label: "Btn", icon: "bolt", ignoreClick: true, drag: 'Docs.Create.ButtonDocument({ _width: 150, _height: 50, _xPadding:10, _yPadding: 10, title: "Button" })' }, { title: "Drag a presentation view", label: "Prezi", icon: "tv", click: 'openOnRight(Doc.UserDoc().activePresentation = getCopy(this.dragFactory, true))', drag: `Doc.UserDoc().activePresentation = getCopy(this.dragFactory,true)`, dragFactory: doc.emptyPresentation as Doc }, { title: "Drag a search box", label: "Query", icon: "search", ignoreClick: true, drag: 'Docs.Create.QueryDocument({ _width: 200, title: "an image of a cat" })' }, - { title: "Drag a scripting box", label: "Script", icon: "terminal", ignoreClick: true, drag: 'Docs.Create.ScriptingDocument(undefined, { _width: 200, _height: 250 title: "untitled script" })' }, + { title: "Drag a scripting box", label: "Script", icon: "terminal", click: 'openOnRight(getCopy(this.dragFactory, true))', drag: 'getCopy(this.dragFactory, true)', dragFactory: doc.emptyScript as Doc }, { title: "Drag an import folder", label: "Load", icon: "cloud-upload-alt", ignoreClick: true, drag: 'Docs.Create.DirectoryImportDocument({ title: "Directory Import", _width: 400, _height: 400 })' }, - { title: "Drag a mobile view", label: "Phone", icon: "phone", ignoreClick: true, drag: 'Doc.UserDoc().activeMobile' }, + { title: "Drag a mobile view", label: "Phone", icon: "mobile", click: 'openOnRight(Doc.UserDoc().activeMobileMenu)', drag: 'this.dragFactory', dragFactory: doc.activeMobileMenu as Doc }, { title: "Drag an instance of the device collection", label: "Buxton", icon: "globe-asia", ignoreClick: true, drag: 'Docs.Create.Buxton()' }, // { title: "use pen", icon: "pen-nib", click: 'activatePen(this.activeInkPen = sameDocs(this.activeInkPen, this) ? undefined : this)', backgroundColor: "blue", ischecked: `sameDocs(this.activeInkPen, this)`, activeInkPen: doc }, // { title: "use highlighter", icon: "highlighter", click: 'activateBrush(this.activeInkPen = sameDocs(this.activeInkPen, this) ? undefined : this,20,this.backgroundColor)', backgroundColor: "yellow", ischecked: `sameDocs(this.activeInkPen, this)`, activeInkPen: doc }, @@ -434,7 +459,7 @@ export class CurrentUserUtils { if (dragCreatorSet === undefined) { doc.myItemCreators = new PrefetchProxy(Docs.Create.MasonryDocument(creatorBtns, { title: "Basic Item Creators", _showTitle: "title", _xMargin: 0, - _autoHeight: true, _width: 500, columnWidth: 35, ignoreClick: true, lockedPosition: true, _chromeStatus: "disabled", + _autoHeight: true, _width: 500, _columnWidth: 35, ignoreClick: true, lockedPosition: true, _chromeStatus: "disabled", dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }), })); } else { @@ -443,25 +468,72 @@ export class CurrentUserUtils { return doc.myItemCreators as Doc; } - static setupMobileButtons(doc: Doc, buttons?: string[]) { - const docProtoData: { title: string, icon: string, drag?: string, ignoreClick?: boolean, click?: string, ischecked?: string, activeInkPen?: Doc, backgroundColor?: string, dragFactory?: Doc }[] = [ - { title: "record", icon: "microphone", ignoreClick: true, click: "FILL" }, - { title: "use pen", icon: "pen-nib", click: 'activatePen(this.activeInkPen = sameDocs(this.activeInkPen, this) ? undefined : this)', backgroundColor: "blue", ischecked: `sameDocs(this.activeInkPen, this)`, activeInkPen: doc }, - { title: "use highlighter", icon: "highlighter", click: 'activateBrush(this.activeInkPen = sameDocs(this.activeInkPen, this) ? undefined : this,20,this.backgroundColor)', backgroundColor: "yellow", ischecked: `sameDocs(this.activeInkPen, this)`, activeInkPen: doc }, - { title: "use eraser", icon: "eraser", click: 'activateEraser(this.activeInkPen = sameDocs(this.activeInkPen, this) ? undefined : this);', ischecked: `sameDocs(this.activeInkPen, this)`, backgroundColor: "pink", activeInkPen: doc }, - { title: "use drag", icon: "mouse-pointer", click: 'deactivateInk();this.activeInkPen = this;', ischecked: `sameDocs(this.activeInkPen, this)`, backgroundColor: "white", activeInkPen: doc }, - // { title: "draw", icon: "pen-nib", click: 'switchMobileView(setupMobileInkingDoc, renderMobileInking, onSwitchMobileInking);', ischecked: `sameDocs(this.activeInkPen, this)`, backgroundColor: "red", activeInkPen: doc }, - { title: "upload", icon: "upload", click: 'switchMobileView(setupMobileUploadDoc, renderMobileUpload, onSwitchMobileUpload);', backgroundColor: "orange" }, - // { title: "upload", icon: "upload", click: 'uploadImageMobile();', backgroundColor: "cyan" }, - ]; - return docProtoData.filter(d => !buttons || !buttons.includes(d.title)).map(data => Docs.Create.FontIconDocument({ - _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: data.click ? "copy" : undefined, title: data.title, icon: data.icon, ignoreClick: data.ignoreClick, - onDragStart: data.drag ? ScriptField.MakeFunction(data.drag) : undefined, onClick: data.click ? ScriptField.MakeScript(data.click) : undefined, - ischecked: data.ischecked ? ComputedField.MakeFunction(data.ischecked) : undefined, activeInkPen: data.activeInkPen, - backgroundColor: data.backgroundColor, removeDropProperties: new List<string>(["dropAction"]), dragFactory: data.dragFactory, + // Sets up mobile menu if it is undefined creates a new one, otherwise returns existing menu + static setupActiveMobileMenu(doc: Doc) { + if (doc.activeMobileMenu === undefined) { + console.log("undefined"); + doc.activeMobileMenu = this.setupMobileMenu(); + } + return doc.activeMobileMenu as Doc; + } + + // Sets up mobileMenu stacking document + static setupMobileMenu() { + const menu = new PrefetchProxy(Docs.Create.StackingDocument(this.setupMobileButtons(), { + _width: 980, ignoreClick: true, lockedPosition: false, _chromeStatus: "disabled", title: "home", _yMargin: 100 })); + return menu; + } + + // SEts up mobile buttons for inside mobile menu + static setupMobileButtons(doc?: Doc, buttons?: string[]) { + const docProtoData: { title: string, icon: string, drag?: string, ignoreClick?: boolean, click?: string, ischecked?: string, activePen?: Doc, backgroundColor?: string, info: string, dragFactory?: Doc }[] = [ + { title: "WORKSPACES", icon: "bars", click: 'switchToMobileLibrary()', backgroundColor: "lightgrey", info: "Access your Workspaces from your mobile, and navigate through all of your documents. " }, + { title: "UPLOAD", icon: "upload", click: 'openMobileUploads()', backgroundColor: "lightgrey", info: "Upload files from your mobile device so they can be accessed on Dash Web." }, + { title: "MOBILE UPLOAD", icon: "mobile", click: 'switchToMobileUploadCollection()', backgroundColor: "lightgrey", info: "Access the collection of your mobile uploads." }, + { title: "RECORD", icon: "microphone", click: 'openMobileAudio()', backgroundColor: "lightgrey", info: "Use your phone to record, dictate and then upload audio onto Dash Web." }, + { title: "PRESENTATION", icon: "desktop", click: 'switchToMobilePresentation()', backgroundColor: "lightgrey", info: "Use your phone as a remote for you presentation." }, + { title: "SETTINGS", icon: "cog", click: 'openMobileSettings()', backgroundColor: "lightgrey", info: "Change your password, log out, or manage your account security." } + ]; + // returns a list of mobile buttons + return docProtoData.filter(d => !buttons || !buttons.includes(d.title)).map(data => + this.mobileButton({ + title: data.title, + lockedPosition: true, + onClick: data.click ? ScriptField.MakeScript(data.click) : undefined, + _backgroundColor: data.backgroundColor + }, + [this.ficon({ ignoreClick: true, icon: data.icon, backgroundColor: "rgba(0,0,0,0)" }), this.mobileTextContainer({}, [this.mobileButtonText({}, data.title), this.mobileButtonInfo({}, data.info)])]) + ); } + // sets up the main document for the mobile button + static mobileButton = (opts: DocumentOptions, docs: Doc[]) => Docs.Create.MulticolumnDocument(docs, { + ...opts, + dropAction: undefined, removeDropProperties: new List<string>(["dropAction"]), _nativeWidth: 900, _nativeHeight: 250, _width: 900, _height: 250, _yMargin: 15, + borderRounding: "5px", boxShadow: "0 0", _chromeStatus: "disabled" + }) as any as Doc + + // sets up the text container for the information contained within the mobile button + static mobileTextContainer = (opts: DocumentOptions, docs: Doc[]) => Docs.Create.MultirowDocument(docs, { + ...opts, + dropAction: undefined, removeDropProperties: new List<string>(["dropAction"]), _nativeWidth: 450, _nativeHeight: 250, _width: 450, _height: 250, _yMargin: 25, + backgroundColor: "rgba(0,0,0,0)", borderRounding: "0", boxShadow: "0 0", _chromeStatus: "disabled", ignoreClick: true + }) as any as Doc + + // Sets up the title of the button + static mobileButtonText = (opts: DocumentOptions, buttonTitle: string) => Docs.Create.TextDocument(buttonTitle, { + ...opts, + dropAction: undefined, title: buttonTitle, _fontSize: 37, _xMargin: 0, _yMargin: 0, ignoreClick: true, _chromeStatus: "disabled", backgroundColor: "rgba(0,0,0,0)" + }) as any as Doc + + // Sets up the description of the button + static mobileButtonInfo = (opts: DocumentOptions, buttonInfo: string) => Docs.Create.TextDocument(buttonInfo, { + ...opts, + dropAction: undefined, title: "info", _fontSize: 25, _xMargin: 0, _yMargin: 0, ignoreClick: true, _chromeStatus: "disabled", backgroundColor: "rgba(0,0,0,0)", _dimMagnitude: 2, + }) as any as Doc + + static setupThumbButtons(doc: Doc) { const docProtoData: { title: string, icon: string, drag?: string, ignoreClick?: boolean, pointerDown?: string, pointerUp?: string, ischecked?: string, clipboard?: Doc, activeInkPen?: Doc, backgroundColor?: string, dragFactory?: Doc }[] = [ { title: "use pen", icon: "pen-nib", pointerUp: "resetPen()", pointerDown: 'setPen(2, this.backgroundColor)', backgroundColor: "blue", ischecked: `sameDocs(this.activeInkPen, this)`, activeInkPen: doc }, @@ -495,31 +567,12 @@ export class CurrentUserUtils { return Cast(userDoc.thumbDoc, Doc); } - static setupMobileDoc(userDoc: Doc) { - return userDoc.activeMoble ?? Docs.Create.MasonryDocument(CurrentUserUtils.setupMobileButtons(userDoc), { - columnWidth: 100, ignoreClick: true, lockedPosition: true, _chromeStatus: "disabled", title: "buttons", _autoHeight: true, _yMargin: 5 - }); - } - - static setupMobileInkingDoc(userDoc: Doc) { - return Docs.Create.FreeformDocument([], { title: "Mobile Inking", backgroundColor: "white" }); + static setupLibrary(userDoc: Doc) { + return CurrentUserUtils.setupWorkspaces(userDoc); } - static setupMobileUploadDoc(userDoc: Doc) { - // const addButton = Docs.Create.FontIconDocument({ onDragStart: ScriptField.MakeScript('addWebToMobileUpload()'), title: "Add Web Doc to Upload Collection", icon: "plus", backgroundColor: "black" }) - const webDoc = Docs.Create.WebDocument("https://www.britannica.com/biography/Miles-Davis", { - title: "Upload Images From the Web", _chromeStatus: "enabled", lockedPosition: true - }); - const uploadDoc = Docs.Create.StackingDocument([], { - title: "Mobile Upload Collection", backgroundColor: "white", lockedPosition: true - }); - return Docs.Create.StackingDocument([webDoc, uploadDoc], { - _width: screen.width, lockedPosition: true, _chromeStatus: "disabled", title: "Upload", _autoHeight: true, _yMargin: 80, backgroundColor: "lightgray" - }); - } - - // setup the Creator button which will display the creator panel. This panel will include the drag creators and the color picker. - // when clicked, this panel will be displayed in the target container (ie, sidebarContainer) + // setup the Creator button which will display the creator panel. This panel will include the drag creators and the color picker. + // when clicked, this panel will be displayed in the target container (ie, sidebarContainer) static async setupToolsBtnPanel(doc: Doc, sidebarContainer: Doc) { // setup a masonry view of all he creators const creatorBtns = await CurrentUserUtils.setupCreatorButtons(doc); @@ -605,6 +658,7 @@ export class CurrentUserUtils { if (doc["tabs-button-library"] === undefined) { const libraryStack = new PrefetchProxy(Docs.Create.TreeDocument([workspaces, documents, recentlyClosed, doc], { title: "Library", _xMargin: 5, _yMargin: 5, _gridGap: 5, forceActive: true, childDropAction: "alias", + treeViewTruncateTitleWidth: 150, lockedPosition: true, boxShadow: "0 0", dontRegisterChildViews: true, targetDropAction: "same" })) as any as Doc; doc["tabs-button-library"] = new PrefetchProxy(Docs.Create.ButtonDocument({ @@ -622,7 +676,7 @@ export class CurrentUserUtils { return doc["tabs-button-library"] as Doc; } - // setup the Search button which will display the search panel. + // setup the Search button which will display the search panel. static setupSearchBtnPanel(doc: Doc, sidebarContainer: Doc) { if (doc["tabs-button-search"] === undefined) { doc["tabs-button-search"] = new PrefetchProxy(Docs.Create.ButtonDocument({ @@ -657,8 +711,8 @@ export class CurrentUserUtils { // Finally, setup the list of buttons to display in the sidebar if (doc["tabs-buttons"] === undefined) { - doc["tabs-buttons"] = new PrefetchProxy(Docs.Create.StackingDocument([searchBtn, libraryBtn, toolsBtn], { - _width: 500, _height: 80, boxShadow: "0 0", _pivotField: "title", hideHeadings: true, ignoreClick: true, _chromeStatus: "view-mode", + doc["tabs-buttons"] = new PrefetchProxy(Docs.Create.StackingDocument([libraryBtn, searchBtn, toolsBtn], { + _width: 500, _height: 80, boxShadow: "0 0", _pivotField: "title", _columnsHideIfEmpty: true, ignoreClick: true, _chromeStatus: "view-mode", title: "sidebar btn row stack", backgroundColor: "dimGray", })); (toolsBtn.onClick as ScriptField).script.run({ this: toolsBtn }); @@ -707,17 +761,19 @@ export class CurrentUserUtils { if (doc.activePresentation === undefined) { doc.activePresentation = Docs.Create.PresDocument(new List<Doc>(), { title: "Presentation", _viewType: CollectionViewType.Stacking, targetDropAction: "alias", - _LODdisable: true, _chromeStatus: "replaced", _showTitle: "title", boxShadow: "0 0" + _chromeStatus: "replaced", _showTitle: "title", boxShadow: "0 0" }); } } + // Right sidebar is where mobile uploads are contained static setupRightSidebar(doc: Doc) { if (doc.rightSidebarCollection === undefined) { - doc.rightSidebarCollection = new PrefetchProxy(Docs.Create.StackingDocument([], { title: "Right Sidebar" })); + doc.rightSidebarCollection = new PrefetchProxy(Docs.Create.StackingDocument([], { title: "Mobile Uploads" })); } } + static setupClickEditorTemplates(doc: Doc) { if (doc["clickFuncs-child"] === undefined) { const openInTarget = Docs.Create.ScriptingDocument(ScriptField.MakeScript( @@ -762,20 +818,26 @@ export class CurrentUserUtils { doc.activeInkPen = doc; doc.activeInkColor = StrCast(doc.activeInkColor, "rgb(0, 0, 0)"); doc.activeInkWidth = StrCast(doc.activeInkWidth, "1"); - doc.activeInkBezier = StrCast(doc.activeInkBezier, ""); + doc.activeInkBezier = StrCast(doc.activeInkBezier, "0"); + doc.activeFillColor = StrCast(doc.activeFillColor, "none"); + doc.activeArrowStart = StrCast(doc.activeArrowStart, "none"); + doc.activeArrowEnd = StrCast(doc.activeArrowEnd, "none"); + doc.activeDash = StrCast(doc.activeDash, "0"); doc.fontSize = NumCast(doc.fontSize, 12); - doc["constants-snapThreshold"] = NumCast(doc["constants-snapThreshold"], 10); // - doc["constants-dragThreshold"] = NumCast(doc["constants-dragThreshold"], 4); // + doc["constants-snapThreshold"] = NumCast(doc["constants-snapThreshold"], 10); // + doc["constants-dragThreshold"] = NumCast(doc["constants-dragThreshold"], 4); // Utils.DRAG_THRESHOLD = NumCast(doc["constants-dragThreshold"]); this.setupDefaultIconTemplates(doc); // creates a set of icon templates triggered by the document deoration icon this.setupDocTemplates(doc); // sets up the template menu of templates this.setupRightSidebar(doc); // sets up the right sidebar collection for mobile upload documents and sharing - this.setupOverlays(doc); // documents in overlay layer + this.setupActiveMobileMenu(doc); // sets up the current mobile menu for Dash Mobile + this.setupOverlays(doc); // documents in overlay layer this.setupDockedButtons(doc); // the bottom bar of font icons this.setupDefaultPresentation(doc); // presentation that's initially triggered await this.setupSidebarButtons(doc); // the pop-out left sidebar of tools/panels doc.globalLinkDatabase = Docs.Prototypes.MainLinkDocument(); doc.globalScriptDatabase = Docs.Prototypes.MainScriptDocument(); + doc.globalGroupDatabase = Docs.Prototypes.MainGroupDocument(); // setup reactions to change the highlights on the undo/redo buttons -- would be better to encode this in the undo/redo buttons, but the undo/redo stacks are not wired up that way yet doc["dockedBtn-undo"] && reaction(() => UndoManager.undoStack.slice(), () => Doc.GetProto(doc["dockedBtn-undo"] as Doc).opacity = UndoManager.CanUndo() ? 1 : 0.4, { fireImmediately: true }); @@ -808,9 +870,5 @@ export class CurrentUserUtils { } } -Scripting.addGlobal(function setupMobileInkingDoc(userDoc: Doc) { return CurrentUserUtils.setupMobileInkingDoc(userDoc); }, - "initializes the Mobile inking document", "(userDoc: Doc)"); -Scripting.addGlobal(function setupMobileUploadDoc(userDoc: Doc) { return CurrentUserUtils.setupMobileUploadDoc(userDoc); }, - "initializes the Mobile upload document", "(userDoc: Doc)"); Scripting.addGlobal(function createNewWorkspace() { return MainView.Instance.createNewWorkspace(); }, - "creates a new workspace when called");
\ No newline at end of file + "creates a new workspace when called"); diff --git a/src/client/util/DocumentManager.ts b/src/client/util/DocumentManager.ts index 78c05f572..1fa5faeb3 100644 --- a/src/client/util/DocumentManager.ts +++ b/src/client/util/DocumentManager.ts @@ -130,7 +130,7 @@ export class DocumentManager { willZoom: boolean, // whether to zoom doc to take up most of screen createViewFunc = DocumentManager.addRightSplit, // how to create a view of the doc if it doesn't exist docContext?: Doc, // context to load that should contain the target - linkId?: string, // link that's being followed + linkDoc?: Doc, // link that's being followed closeContextIfNotFound: boolean = false, // after opening a context where the document should be, this determines whether the context should be closed if the Doc isn't actually there originatingDoc: Opt<Doc> = undefined, // doc that initiated the display of the target odoc finished?: () => void @@ -140,13 +140,13 @@ export class DocumentManager { const highlight = () => { const finalDocView = getFirstDocView(targetDoc); if (finalDocView) { - finalDocView.layoutDoc.scrollToLinkID = linkId; + finalDocView.layoutDoc.scrollToLinkID = linkDoc?.[Id]; Doc.linkFollowHighlight(finalDocView.props.Document); } }; const docView = getFirstDocView(targetDoc, originatingDoc); let annotatedDoc = await Cast(targetDoc.annotationOn, Doc); - if (annotatedDoc) { + if (annotatedDoc && !linkDoc?.isPushpin) { const first = getFirstDocView(annotatedDoc); if (first) { annotatedDoc = first.props.Document; @@ -156,7 +156,11 @@ export class DocumentManager { } } if (docView) { // we have a docView already and aren't forced to create a new one ... just focus on the document. TODO move into view if necessary otherwise just highlight? - docView.props.focus(docView.props.Document, willZoom, undefined, focusAndFinish); + if (linkDoc?.isPushpin) docView.props.Document.hidden = !docView.props.Document.hidden; + else { + docView.props.Document.hidden && (docView.props.Document.hidden = undefined); + docView.props.focus(docView.props.Document, willZoom, undefined, focusAndFinish); + } highlight(); } else { const contextDocs = docContext ? await DocListCastAsync(docContext.data) : undefined; @@ -170,7 +174,7 @@ export class DocumentManager { const targetDocContextView = getFirstDocView(targetDocContext); targetDocContext._scrollY = 0; // this will force PDFs to activate and load their annotations / allow scrolling if (targetDocContextView) { // we found a context view and aren't forced to create a new one ... focus on the context first.. - targetDocContext.panTransformType = "Ease"; + targetDocContext._viewTransition = "transform 500ms"; targetDocContextView.props.focus(targetDocContextView.props.Document, willZoom); // now find the target document within the context @@ -195,7 +199,7 @@ export class DocumentManager { const finalDocView = getFirstDocView(targetDoc); const finalDocContextView = getFirstDocView(targetDocContext); setTimeout(() => // if not, wait a bit to see if the context can be loaded (e.g., a PDF). wait interval heurisitic tries to guess how we're animating based on what's just become visible - this.jumpToDocument(targetDoc, willZoom, createViewFunc, undefined, linkId, true, undefined, finished), // pass true this time for closeContextIfNotFound + this.jumpToDocument(targetDoc, willZoom, createViewFunc, undefined, linkDoc, true, undefined, finished), // pass true this time for closeContextIfNotFound finalDocView ? 0 : finalDocContextView ? 250 : 2000); // so call jump to doc again and if the doc isn't found, it will be created. }, 0); } @@ -224,7 +228,7 @@ export class DocumentManager { containerDoc.currentTimecode = targetTimecode; const targetContext = await target?.context as Doc; const targetNavContext = !Doc.AreProtosEqual(targetContext, currentContext) ? targetContext : undefined; - DocumentManager.Instance.jumpToDocument(target, zoom, (doc, finished) => createViewFunc(doc, StrCast(linkDoc.followLinkLocation, "onRight"), finished), targetNavContext, linkDoc[Id], undefined, doc, finished); + DocumentManager.Instance.jumpToDocument(target, zoom, (doc, finished) => createViewFunc(doc, StrCast(linkDoc.followLinkLocation, "onRight"), finished), targetNavContext, linkDoc, undefined, doc, finished); } else { finished?.(); } diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index 417ddf989..2ceafff30 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -19,8 +19,6 @@ export function SetupDrag( docFunc: () => Doc | Promise<Doc> | undefined, moveFunc?: DragManager.MoveFunction, dropAction?: dropActionType, - treeViewId?: string, - dontHideOnDrop?: boolean, dragStarted?: () => void ) { const onRowMove = async (e: PointerEvent) => { @@ -34,8 +32,6 @@ export function SetupDrag( const dragData = new DragManager.DocumentDragData([doc]); dragData.dropAction = dropAction; dragData.moveDocument = moveFunc; - dragData.treeViewId = treeViewId; - dragData.dontHideOnDrop = dontHideOnDrop; DragManager.StartDocumentDrag([_reference.current!], dragData, e.x, e.y); dragStarted?.(); } @@ -128,7 +124,7 @@ export namespace DragManager { draggedDocuments: Doc[]; droppedDocuments: Doc[]; dragDivName?: string; - treeViewId?: string; + treeViewDoc?: Doc; dontHideOnDrop?: boolean; offset: number[]; dropAction: dropActionType; @@ -206,7 +202,6 @@ export namespace DragManager { dropDoc instanceof Doc && DocUtils.MakeLinkToActiveAudio(dropDoc); return dropDoc; }; - const batch = UndoManager.StartBatch("dragging"); const finishDrag = (e: DragCompleteEvent) => { const docDragData = e.docDragData; if (docDragData && !docDragData.droppedDocuments.length) { @@ -220,7 +215,6 @@ export namespace DragManager { const remProps = (dragData?.removeDropProperties || []).concat(Array.from(dragProps)); remProps.map(prop => drop[prop] = undefined); }); - batch.end(); } return e; }; @@ -319,6 +313,7 @@ export namespace DragManager { export let docsBeingDragged: Doc[] = []; export let CanEmbed = false; export function StartDrag(eles: HTMLElement[], dragData: { [id: string]: any }, downX: number, downY: number, options?: DragOptions, finishDrag?: (dropData: DragCompleteEvent) => void) { + const batch = UndoManager.StartBatch("dragging"); eles = eles.filter(e => e); CanEmbed = false; if (!dragDiv) { @@ -453,6 +448,7 @@ export namespace DragManager { document.removeEventListener("pointermove", moveHandler, true); document.removeEventListener("pointerup", upHandler); SnappingManager.clearSnapLines(); + batch.end(); }); AbortDrag = () => { diff --git a/src/client/util/GroupManager.scss b/src/client/util/GroupManager.scss new file mode 100644 index 000000000..544a79e98 --- /dev/null +++ b/src/client/util/GroupManager.scss @@ -0,0 +1,136 @@ +@import "../views/globalCssVariables"; + +.group-interface { + background-color: whitesmoke !important; + color: grey; + width: 450px; + height: 300px; + + .dialogue-box { + width: 450; + height: 300; + } + + button { + background: $lighter-alt-accent; + outline: none; + border-radius: 5px; + border: 0px; + color: #fcfbf7; + text-transform: uppercase; + letter-spacing: 2px; + font-size: 75%; + padding: 10px; + margin: 10px; + transition: transform 0.2s; + margin: 2px; + } +} + +.group-interface { + display: flex; + flex-direction: column; + + .overlay { + transform: translate(-20px, -20px); + border-radius: 10px; + } + + button { + width: 100%; + align-self: center; + background: $darker-alt-accent; + } + + .delete-button { + background: rgb(227, 86, 86); + } + + .close-button { + position: absolute; + right: 1em; + top: 1em; + cursor: pointer; + z-index: 999; + } + + .group-heading { + letter-spacing: .5em; + } + + + .group-body { + display: flex; + justify-content: space-between; + max-height: 80%; + + .group-create { + display: flex; + flex-direction: column; + flex-basis: 30%; + margin-left: 5px; + + input { + border-radius: 5px; + border: none; + padding: 4px; + min-width: 100%; + margin: 4px 0 4px 0; + } + + } + + .group-content { + padding-left: 1em; + padding-right: 1em; + justify-content: space-around; + text-align: left; + + overflow-y: auto; + width: 100%; + + .group-row { + display: flex; + position: relative; + margin-bottom: 5px; + min-height: 40px; + border: 1px solid; + border-radius: 10px; + align-items: center; + + .group-name { + position: relative; + max-width: 65%; + left: 10; + } + + button { + position: absolute; + width: 30%; + right: 2; + margin-top: 0; + } + } + + ::placeholder { + color: $intermediate-color; + } + + input { + border-radius: 5px; + border: none; + padding: 4px; + min-width: 100%; + margin: 2px 0; + } + + } + } + + h1 { + color: $dark-color; + text-transform: uppercase; + letter-spacing: 2px; + font-size: 120%; + } +}
\ No newline at end of file diff --git a/src/client/util/GroupManager.tsx b/src/client/util/GroupManager.tsx new file mode 100644 index 000000000..7c68fc2a0 --- /dev/null +++ b/src/client/util/GroupManager.tsx @@ -0,0 +1,360 @@ +import * as React from "react"; +import { observable, action, runInAction, computed } from "mobx"; +import { SelectionManager } from "./SelectionManager"; +import MainViewModal from "../views/MainViewModal"; +import { observer } from "mobx-react"; +import { Doc, DocListCast, Opt } from "../../fields/Doc"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import * as fa from '@fortawesome/free-solid-svg-icons'; +import { library } from "@fortawesome/fontawesome-svg-core"; +import SharingManager, { User } from "./SharingManager"; +import { Utils } from "../../Utils"; +import * as RequestPromise from "request-promise"; +import Select from 'react-select'; +import "./GroupManager.scss"; +import { StrCast } from "../../fields/Types"; +import GroupMemberView from "./GroupMemberView"; + +library.add(fa.faWindowClose); + +export interface UserOptions { + label: string; + value: string; +} + +@observer +export default class GroupManager extends React.Component<{}> { + + static Instance: GroupManager; + @observable isOpen: boolean = false; // whether the GroupManager is to be displayed or not. + @observable private dialogueBoxOpacity: number = 1; // opacity of the dialogue box div of the MainViewModal. + @observable private overlayOpacity: number = 0.4; // opacity of the overlay div of the MainViewModal. + @observable private users: string[] = []; // list of users populated from the database. + @observable private selectedUsers: UserOptions[] | null = null; // list of users selected in the "Select users" dropdown. + @observable currentGroup: Opt<Doc>; // the currently selected group. + private inputRef: React.RefObject<HTMLInputElement> = React.createRef(); // the ref for the input box. + + constructor(props: Readonly<{}>) { + super(props); + GroupManager.Instance = this; + } + + // sets up the list of users + componentDidMount() { + this.populateUsers().then(resolved => runInAction(() => this.users = resolved)); + } + + /** + * Fetches the list of users stored on the database and @returns a list of the emails. + */ + populateUsers = async () => { + const userList: User[] = JSON.parse(await RequestPromise.get(Utils.prepend("/getUsers"))); + const currentUserIndex = userList.findIndex(user => user.email === Doc.CurrentUserEmail); + currentUserIndex !== -1 && userList.splice(currentUserIndex, 1); + return userList.map(user => user.email); + } + + /** + * @returns the options to be rendered in the dropdown menu to add users and create a group. + */ + @computed get options() { + return this.users.map(user => ({ label: user, value: user })); + } + + /** + * Makes the GroupManager visible. + */ + @action + open = () => { + SelectionManager.DeselectAll(); + this.isOpen = true; + } + + /** + * Hides the GroupManager. + */ + @action + close = () => { + this.isOpen = false; + this.currentGroup = undefined; + } + + /** + * @returns the database of groups. + */ + get GroupManagerDoc(): Doc | undefined { + return Doc.UserDoc().globalGroupDatabase as Doc; + } + + /** + * @returns a list of all group documents. + */ + private getAllGroups(): Doc[] { + const groupDoc = this.GroupManagerDoc; + return groupDoc ? DocListCast(groupDoc.data) : []; + } + + /** + * @returns a group document based on the group name. + * @param groupName + */ + private getGroup(groupName: string): Doc | undefined { + const groupDoc = this.getAllGroups().find(group => group.groupName === groupName); + return groupDoc; + } + + /** + * @returns a readonly copy of a single group document + */ + getGroupCopy(groupName: string): Doc | undefined { + const groupDoc = this.getGroup(groupName); + if (groupDoc) { + const { members, owners } = groupDoc; + return Doc.assign(new Doc, { groupName, members: StrCast(members), owners: StrCast(owners) }); + } + return undefined; + } + /** + * @returns a readonly copy of the list of group documents + */ + getAllGroupsCopy(): Doc[] { + return this.getAllGroups().map(({ groupName, owners, members }) => + Doc.assign(new Doc, { groupName: (StrCast(groupName)), owners: (StrCast(owners)), members: (StrCast(members)) }) + ); + } + + /** + * @returns the members of the admin group. + */ + get adminGroupMembers(): string[] { + return this.getGroup("admin") ? JSON.parse(StrCast(this.getGroup("admin")!.members)) : ""; + } + + /** + * @returns a boolean indicating whether the current user has access to edit group documents. + * @param groupDoc + */ + hasEditAccess(groupDoc: Doc): boolean { + if (!groupDoc) return false; + const accessList: string[] = JSON.parse(StrCast(groupDoc.owners)); + return accessList.includes(Doc.CurrentUserEmail) || this.adminGroupMembers?.includes(Doc.CurrentUserEmail); + } + + /** + * Helper method that sets up the group document. + * @param groupName + * @param memberEmails + */ + createGroupDoc(groupName: string, memberEmails: string[] = []) { + const groupDoc = new Doc; + groupDoc.groupName = groupName; + groupDoc.owners = JSON.stringify([Doc.CurrentUserEmail]); + groupDoc.members = JSON.stringify(memberEmails); + this.addGroup(groupDoc); + } + + /** + * Helper method that adds a group document to the database of group documents and @returns whether it was successfully added or not. + * @param groupDoc + */ + addGroup(groupDoc: Doc): boolean { + if (this.GroupManagerDoc) { + Doc.AddDocToList(this.GroupManagerDoc, "data", groupDoc); + return true; + } + return false; + } + + /** + * Deletes a group from the database of group documents and @returns whether the group was deleted or not. + * @param group + */ + deleteGroup(group: Doc): boolean { + if (group) { + if (this.GroupManagerDoc && this.hasEditAccess(group)) { + Doc.RemoveDocFromList(this.GroupManagerDoc, "data", group); + SharingManager.Instance.setInternalGroupSharing(group, "Not Shared"); + if (group === this.currentGroup) { + runInAction(() => this.currentGroup = undefined); + } + return true; + } + } + return false; + } + + /** + * Adds a member to a group. + * @param groupDoc + * @param email + */ + addMemberToGroup(groupDoc: Doc, email: string) { + if (this.hasEditAccess(groupDoc)) { + const memberList: string[] = JSON.parse(StrCast(groupDoc.members)); + !memberList.includes(email) && memberList.push(email); + groupDoc.members = JSON.stringify(memberList); + } + } + + /** + * Removes a member from the group. + * @param groupDoc + * @param email + */ + removeMemberFromGroup(groupDoc: Doc, email: string) { + if (this.hasEditAccess(groupDoc)) { + const memberList: string[] = JSON.parse(StrCast(groupDoc.members)); + const index = memberList.indexOf(email); + index !== -1 && memberList.splice(index, 1); + groupDoc.members = JSON.stringify(memberList); + } + } + + /** + * Handles changes in the users selected in the "Select users" dropdown. + * @param selectedOptions + */ + @action + handleChange = (selectedOptions: any) => { + this.selectedUsers = selectedOptions as UserOptions[]; + } + + /** + * Creates the group when the enter key has been pressed (when in the input). + * @param e + */ + handleKeyDown = (e: React.KeyboardEvent) => { + e.key === "Enter" && this.createGroup(); + } + + /** + * Handles the input of required fields in the setup of a group and resets the relevant variables. + */ + @action + createGroup = () => { + if (!this.inputRef.current?.value) { + alert("Please enter a group name"); + return; + } + if (this.getAllGroups().find(group => group.groupName === this.inputRef.current!.value)) { // why do I need a null check here? + alert("Please select a unique group name"); + return; + } + this.createGroupDoc(this.inputRef.current.value, this.selectedUsers?.map(user => user.value)); + this.selectedUsers = null; + this.inputRef.current.value = ""; + } + + /** + * A getter that @returns the interface rendered to view an individual group. + */ + private get editingInterface() { + const members: string[] = this.currentGroup ? JSON.parse(StrCast(this.currentGroup.members)) : []; + const options: UserOptions[] = this.currentGroup ? this.options.filter(option => !(JSON.parse(StrCast(this.currentGroup!.members)) as string[]).includes(option.value)) : []; + return (!this.currentGroup ? null : + <div className="editing-interface"> + <div className="editing-header"> + <b>{this.currentGroup.groupName}</b> + <div className={"close-button"} onClick={action(() => this.currentGroup = undefined)}> + <FontAwesomeIcon icon={fa.faWindowClose} size={"lg"} /> + </div> + + {this.hasEditAccess(this.currentGroup) ? + <div className="group-buttons"> + <div className="add-member-dropdown"> + <Select + // isMulti={true} + isSearchable={true} + options={options} + onChange={selectedOption => this.addMemberToGroup(this.currentGroup!, (selectedOption as UserOptions).value)} + placeholder={"Add members"} + value={null} + closeMenuOnSelect={true} + /> + </div> + <button onClick={() => this.deleteGroup(this.currentGroup!)}>Delete group</button> + </div> : + null} + </div> + <div className="editing-contents"> + {members.map(member => ( + <div className="editing-row"> + <div className="user-email"> + {member} + </div> + {this.hasEditAccess(this.currentGroup!) ? <button onClick={() => this.removeMemberFromGroup(this.currentGroup!, member)}> Remove </button> : null} + </div> + ))} + </div> + </div> + ); + + } + + /** + * A getter that @returns the main interface for the GroupManager. + */ + private get groupInterface() { + return ( + <div className="group-interface"> + {/* <MainViewModal + contents={this.editingInterface} + isDisplayed={this.currentGroup ? true : false} + interactive={true} + dialogueBoxDisplayedOpacity={this.dialogueBoxOpacity} + overlayDisplayedOpacity={this.overlayOpacity} + /> */} + {this.currentGroup ? + <GroupMemberView + group={this.currentGroup} + onCloseButtonClick={() => this.currentGroup = undefined} + /> + : null} + <div className="group-heading"> + <h1>Groups</h1> + <div className={"close-button"} onClick={this.close}> + <FontAwesomeIcon icon={fa.faWindowClose} size={"lg"} /> + </div> + </div> + <div className="group-body"> + <div className="group-create"> + <button onClick={this.createGroup}>Create group</button> + <input ref={this.inputRef} onKeyDown={this.handleKeyDown} type="text" placeholder="Group name" /> + <Select + isMulti={true} + isSearchable={true} + options={this.options} + onChange={this.handleChange} + placeholder={"Select users"} + value={this.selectedUsers} + closeMenuOnSelect={false} + /> + </div> + <div className="group-content"> + {this.getAllGroups().map(group => + <div className="group-row"> + <div className="group-name">{group.groupName}</div> + <button onClick={action(() => this.currentGroup = group)}> + {this.hasEditAccess(group) ? "Edit" : "View"} + </button> + </div> + )} + </div> + </div> + </div> + ); + } + + render() { + return ( + <MainViewModal + contents={this.groupInterface} + isDisplayed={this.isOpen} + interactive={true} + dialogueBoxDisplayedOpacity={this.dialogueBoxOpacity} + overlayDisplayedOpacity={this.overlayOpacity} + /> + ); + } + +}
\ No newline at end of file diff --git a/src/client/util/GroupMemberView.scss b/src/client/util/GroupMemberView.scss new file mode 100644 index 000000000..7833c485f --- /dev/null +++ b/src/client/util/GroupMemberView.scss @@ -0,0 +1,68 @@ +@import "../views/globalCssVariables"; + +.editing-interface { + background-color: whitesmoke !important; + color: grey; + width: 100%; + height: 100%; + + button { + background: $darker-alt-accent; + outline: none; + border-radius: 5px; + border: 0px; + color: #fcfbf7; + text-transform: uppercase; + letter-spacing: 2px; + font-size: 75%; + padding: 10px; + margin: 10px; + transition: transform 0.2s; + margin: 2px; + } + + .memberView-closeButton { + position: absolute; + right: 1em; + top: 1em; + cursor: pointer; + z-index: 1000; + } + + .editing-header { + margin-bottom: 5; + + .group-buttons { + display: flex; + margin-top: 5; + + .add-member-dropdown { + width: 100%; + margin: 0 5; + } + } + } + + .editing-contents { + overflow-y: auto; + // max-height: 67%; + height: 67%; + width: 100%; + + .editing-row { + display: flex; + align-items: center; + // border: 1px solid; + // border-radius: 10px; + + .user-email { + // position: relative; + min-width: 65%; + word-break: break-all; + padding: 0 5; + } + } + } + + +}
\ No newline at end of file diff --git a/src/client/util/GroupMemberView.tsx b/src/client/util/GroupMemberView.tsx new file mode 100644 index 000000000..b2d75158e --- /dev/null +++ b/src/client/util/GroupMemberView.tsx @@ -0,0 +1,75 @@ +import * as React from "react"; +import MainViewModal from "../views/MainViewModal"; +import { observer } from "mobx-react"; +import GroupManager, { UserOptions } from "./GroupManager"; +import { library } from "@fortawesome/fontawesome-svg-core"; +import { StrCast } from "../../fields/Types"; +import { action } from "mobx"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import * as fa from '@fortawesome/free-solid-svg-icons'; +import Select from "react-select"; +import { Doc, Opt } from "../../fields/Doc"; +import "./GroupMemberView.scss"; + +library.add(fa.faWindowClose); + +interface GroupMemberViewProps { + group: Doc; + onCloseButtonClick: () => void; +} + +@observer +export default class GroupMemberView extends React.Component<GroupMemberViewProps> { + + private get editingInterface() { + const members: string[] = this.props.group ? JSON.parse(StrCast(this.props.group.members)) : []; + const options: UserOptions[] = this.props.group ? GroupManager.Instance.options.filter(option => !(JSON.parse(StrCast(this.props.group.members)) as string[]).includes(option.value)) : []; + return (!this.props.group ? null : + <div className="editing-interface"> + <div className="editing-header"> + <b>{this.props.group.groupName}</b> + <div className={"memberView-closeButton"} onClick={action(this.props.onCloseButtonClick)}> + <FontAwesomeIcon icon={fa.faWindowClose} size={"lg"} /> + </div> + + {GroupManager.Instance.hasEditAccess(this.props.group) ? + <div className="group-buttons"> + <div className="add-member-dropdown"> + <Select + isSearchable={true} + options={options} + onChange={selectedOption => GroupManager.Instance.addMemberToGroup(this.props.group, (selectedOption as UserOptions).value)} + placeholder={"Add members"} + value={null} + closeMenuOnSelect={true} + /> + </div> + <button onClick={() => GroupManager.Instance.deleteGroup(this.props.group)}>Delete group</button> + </div> : + null} + </div> + <div className="editing-contents"> + {members.map(member => ( + <div className="editing-row"> + <div className="user-email"> + {member} + </div> + {GroupManager.Instance.hasEditAccess(this.props.group) ? <button onClick={() => GroupManager.Instance.removeMemberFromGroup(this.props.group, member)}> Remove </button> : null} + </div> + ))} + </div> + </div> + ); + + } + + render() { + return <MainViewModal + isDisplayed={true} + interactive={true} + contents={this.editingInterface} + />; + } + + +}
\ No newline at end of file diff --git a/src/client/util/Import & Export/DirectoryImportBox.tsx b/src/client/util/Import & Export/DirectoryImportBox.tsx index af6c57e68..77f13e9f4 100644 --- a/src/client/util/Import & Export/DirectoryImportBox.tsx +++ b/src/client/util/Import & Export/DirectoryImportBox.tsx @@ -161,7 +161,7 @@ export class DirectoryImportBox extends React.Component<FieldViewProps> { importContainer = Docs.Create.SchemaDocument(headers, docs, options); } runInAction(() => this.phase = 'External: uploading files to Google Photos...'); - importContainer.singleColumn = false; + importContainer._columnsStack = false; await GooglePhotos.Export.CollectionToAlbum({ collection: importContainer }); Doc.AddDocToList(Doc.GetProto(parent.props.Document), "data", importContainer); !this.persistent && this.props.removeDocument && this.props.removeDocument(doc); diff --git a/src/client/util/InteractionUtils.scss b/src/client/util/InteractionUtils.scss new file mode 100644 index 000000000..6707157d4 --- /dev/null +++ b/src/client/util/InteractionUtils.scss @@ -0,0 +1,4 @@ +.halo { + opacity: 0.2; + stroke: black; +}
\ No newline at end of file diff --git a/src/client/util/InteractionUtils.tsx b/src/client/util/InteractionUtils.tsx index df792c9c0..02b444cd3 100644 --- a/src/client/util/InteractionUtils.tsx +++ b/src/client/util/InteractionUtils.tsx @@ -1,6 +1,8 @@ import React = require("react"); import * as beziercurve from 'bezier-curve'; import * as fitCurve from 'fit-curve'; +import "./InteractionUtils.scss"; +import { Utils } from "../../Utils"; export namespace InteractionUtils { export const MOUSETYPE = "mouse"; @@ -25,7 +27,7 @@ export namespace InteractionUtils { export interface MultiTouchEventDisposer { (): void; } /** - * + * * @param element - element to turn into a touch target * @param startFunc - event handler, typically Touchable.onTouchStart (classes that inherit touchable can pass in this.onTouchStart) */ @@ -89,15 +91,17 @@ export namespace InteractionUtils { return myTouches; } - export function CreatePolyline(points: { X: number, Y: number }[], left: number, top: number, color: string, width: number, strokeWidth: number, bezier: string, scalex: number, scaley: number, shape: string, pevents: string, drawHalo: boolean) { + export function CreatePolyline(points: { X: number, Y: number }[], left: number, top: number, + color: string, width: number, strokeWidth: number, bezier: string, fill: string, arrowStart: string, arrowEnd: string, + dash: string, scalex: number, scaley: number, shape: string, pevents: string, drawHalo: boolean, nodefs: boolean) { let pts: { X: number; Y: number; }[] = []; if (shape) { //if any of the shape are true pts = makePolygon(shape, points); } else if (points.length > 1 && points[points.length - 1].X === points[0].X && points[points.length - 1].Y === points[0].Y) { //pointer is up (first and last points are the same) - points.pop(); const newPoints = points.reduce((p, pts) => { p.push([pts.X, pts.Y]); return p; }, [] as number[][]); + newPoints.pop(); const bezierCurves = fitCurve(newPoints, parseInt(bezier)); for (const curve of bezierCurves) { @@ -111,25 +115,55 @@ export namespace InteractionUtils { } const strpts = pts.reduce((acc: string, pt: { X: number, Y: number }) => acc + `${(pt.X - left - width / 2) * scalex + width / 2}, - ${(pt.Y - top - width / 2) * scaley + width / 2} `, ""); + ${(pt.Y - top - width / 2) * scaley + width / 2} `, ""); + const dashArray = String(Number(width) * Number(dash)); + const defGuid = Utils.GenerateGuid(); + const arrowDim = Math.max(0.5, 8 / Math.log(Math.max(2, strokeWidth))); + return (<svg fill={fill === "none" ? color : fill}> {/* setting the svg fill sets the arrowhead fill */} + {nodefs ? (null) : <defs> + {arrowStart !== "dot" && arrowEnd !== "dot" ? (null) : <marker id={`dot${defGuid}`} orient="auto" overflow="visible"> + <circle r={1} fill="context-stroke" /> + </marker>} + {arrowStart !== "arrowHead" && arrowEnd !== "arrowHead" ? (null) : <marker id={`arrowHead${defGuid}`} orient="auto" overflow="visible" refX="1.6" refY="0" markerWidth="10" markerHeight="7"> + <polygon points={`${arrowDim} ${-Math.max(1, arrowDim / 2)}, ${arrowDim} ${Math.max(1, arrowDim / 2)}, -1 0`} /> + </marker>} + {arrowStart !== "arrowEnd" && arrowEnd !== "arrowEnd" ? (null) : <marker id={`arrowEnd${defGuid}`} orient="auto" overflow="visible" refX="1.6" refY="0" markerWidth="10" markerHeight="7"> + <polygon points={`${2 - arrowDim} ${-Math.max(1, arrowDim / 2)}, ${2 - arrowDim} ${Math.max(1, arrowDim / 2)}, 3 0`} /> + </marker>} + </defs>} - return ( <polyline points={strpts} style={{ - filter: drawHalo ? "url(#dangerShine)" : undefined, - fill: "none", + filter: drawHalo ? "url(#inkSelectionHalo)" : undefined, + fill, opacity: strokeWidth !== width ? 0.5 : undefined, pointerEvents: pevents as any, stroke: color ?? "rgb(0, 0, 0)", strokeWidth: strokeWidth, strokeLinejoin: "round", - strokeLinecap: "round" + strokeLinecap: "round", + strokeDasharray: dashArray }} + markerStart={`url(#${arrowStart + defGuid})`} + markerEnd={`url(#${arrowEnd + defGuid})`} /> - ); + + </svg>); } + // export function makeArrow() { + // return ( + // InkOptionsMenu.Instance.getColors().map(color => { + // const id1 = "arrowHeadTest" + color; + // console.log(color); + // <marker id={id1} orient="auto" overflow="visible" refX="0" refY="1" markerWidth="10" markerHeight="7"> + // <polygon points="0 0, 3 1, 0 2" fill={"#" + color} /> + // </marker>; + // }) + // ); + // } + export function makePolygon(shape: string, points: { X: number, Y: number }[]) { if (points.length > 1 && points[points.length - 1].X === points[0].X && points[points.length - 1].Y + 1 === points[0].Y) { //pointer is up (first and last points are the same) @@ -199,24 +233,24 @@ export namespace InteractionUtils { } points.push({ X: Math.sqrt(Math.pow(radius, 2) - (Math.pow((top - centerY), 2))) + centerX, Y: top }); return points; - case "arrow": - const x1 = left; - const y1 = top; - const x2 = right; - const y2 = bottom; - const L1 = Math.sqrt(Math.pow(Math.abs(x1 - x2), 2) + (Math.pow(Math.abs(y1 - y2), 2))); - const L2 = L1 / 5; - const angle = 0.785398; - const x3 = x2 + (L2 / L1) * ((x1 - x2) * Math.cos(angle) + (y1 - y2) * Math.sin(angle)); - const y3 = y2 + (L2 / L1) * ((y1 - y2) * Math.cos(angle) - (x1 - x2) * Math.sin(angle)); - const x4 = x2 + (L2 / L1) * ((x1 - x2) * Math.cos(angle) - (y1 - y2) * Math.sin(angle)); - const y4 = y2 + (L2 / L1) * ((y1 - y2) * Math.cos(angle) + (x1 - x2) * Math.sin(angle)); - points.push({ X: x1, Y: y1 }); - points.push({ X: x2, Y: y2 }); - points.push({ X: x3, Y: y3 }); - points.push({ X: x4, Y: y4 }); - points.push({ X: x2, Y: y2 }); - return points; + // case "arrow": + // const x1 = left; + // const y1 = top; + // const x2 = right; + // const y2 = bottom; + // const L1 = Math.sqrt(Math.pow(Math.abs(x1 - x2), 2) + (Math.pow(Math.abs(y1 - y2), 2))); + // const L2 = L1 / 5; + // const angle = 0.785398; + // const x3 = x2 + (L2 / L1) * ((x1 - x2) * Math.cos(angle) + (y1 - y2) * Math.sin(angle)); + // const y3 = y2 + (L2 / L1) * ((y1 - y2) * Math.cos(angle) - (x1 - x2) * Math.sin(angle)); + // const x4 = x2 + (L2 / L1) * ((x1 - x2) * Math.cos(angle) - (y1 - y2) * Math.sin(angle)); + // const y4 = y2 + (L2 / L1) * ((y1 - y2) * Math.cos(angle) + (x1 - x2) * Math.sin(angle)); + // points.push({ X: x1, Y: y1 }); + // points.push({ X: x2, Y: y2 }); + // points.push({ X: x3, Y: y3 }); + // points.push({ X: x4, Y: y4 }); + // points.push({ X: x2, Y: y2 }); + // return points; case "line": points.push({ X: left, Y: top }); points.push({ X: right, Y: bottom }); @@ -244,8 +278,8 @@ export namespace InteractionUtils { /** * Returns euclidean distance between two points - * @param pt1 - * @param pt2 + * @param pt1 + * @param pt2 */ export function TwoPointEuclidist(pt1: React.Touch, pt2: React.Touch): number { return Math.sqrt(Math.pow(pt1.clientX - pt2.clientX, 2) + Math.pow(pt1.clientY - pt2.clientY, 2)); @@ -376,4 +410,4 @@ export namespace InteractionUtils { // } // } } -}
\ No newline at end of file +} diff --git a/src/client/util/LinkManager.ts b/src/client/util/LinkManager.ts index 47b2541bd..749fabfcc 100644 --- a/src/client/util/LinkManager.ts +++ b/src/client/util/LinkManager.ts @@ -41,24 +41,17 @@ export class LinkManager { } public addLink(linkDoc: Doc): boolean { - const linkList = LinkManager.Instance.getAllLinks(); - linkList.push(linkDoc); if (LinkManager.Instance.LinkManagerDoc) { - LinkManager.Instance.LinkManagerDoc.data = new List<Doc>(linkList); + Doc.AddDocToList(LinkManager.Instance.LinkManagerDoc, "data", linkDoc); return true; } return false; } public deleteLink(linkDoc: Doc): boolean { - const linkList = LinkManager.Instance.getAllLinks(); - const index = LinkManager.Instance.getAllLinks().indexOf(linkDoc); - if (index > -1) { - linkList.splice(index, 1); - if (LinkManager.Instance.LinkManagerDoc) { - LinkManager.Instance.LinkManagerDoc.data = new List<Doc>(linkList); - return true; - } + if (LinkManager.Instance.LinkManagerDoc && linkDoc instanceof Doc) { + Doc.RemoveDocFromList(LinkManager.Instance.LinkManagerDoc, "data", linkDoc); + return true; } return false; } @@ -70,6 +63,9 @@ export class LinkManager { const protomatch2 = Doc.AreProtosEqual(anchor, Cast(link.anchor2, Doc, null)); return protomatch1 || protomatch2 || Doc.AreProtosEqual(link, anchor); }); + DocListCast(anchor[Doc.LayoutFieldKey(anchor) + "-annotations"]).map(anno => { + related.push(...LinkManager.Instance.getAllRelatedLinks(anno)); + }); return related; } diff --git a/src/client/util/SearchUtil.ts b/src/client/util/SearchUtil.ts index 5679c0a14..1ac68480e 100644 --- a/src/client/util/SearchUtil.ts +++ b/src/client/util/SearchUtil.ts @@ -74,7 +74,7 @@ export namespace SearchUtil { const docs = ids.map((id: string) => docMap[id]).map(doc => doc as Doc); for (let i = 0; i < ids.length; i++) { const testDoc = docs[i]; - if (testDoc instanceof Doc && testDoc.type !== DocumentType.KVP && (options.allowAliases || theDocs.findIndex(d => Doc.AreProtosEqual(d, testDoc)) === -1)) { + if (testDoc instanceof Doc && testDoc.type !== DocumentType.KVP && (options.allowAliases || testDoc.proto === undefined || theDocs.findIndex(d => Doc.AreProtosEqual(d, testDoc)) === -1)) { theDocs.push(testDoc); theLines.push([]); } diff --git a/src/client/util/SelectionManager.ts b/src/client/util/SelectionManager.ts index eb905d237..024532f90 100644 --- a/src/client/util/SelectionManager.ts +++ b/src/client/util/SelectionManager.ts @@ -3,6 +3,8 @@ import { Doc } from "../../fields/Doc"; import { DocumentView } from "../views/nodes/DocumentView"; import { computedFn } from "mobx-utils"; import { List } from "../../fields/List"; +import { Scripting } from "./Scripting"; +import { DocumentManager } from "./DocumentManager"; export namespace SelectionManager { @@ -10,17 +12,12 @@ export namespace SelectionManager { @observable IsDragging: boolean = false; SelectedDocuments: ObservableMap<DocumentView, boolean> = new ObservableMap(); - clearSelection() { - if (window.getSelection) { window.getSelection()?.removeAllRanges(); } - else if (document.getSelection()) { document.getSelection()?.empty(); } - } @action SelectDoc(docView: DocumentView, ctrlPressed: boolean): void { // if doc is not in SelectedDocuments, add it if (!manager.SelectedDocuments.get(docView)) { if (!ctrlPressed) { this.DeselectAll(); - this.clearSelection(); } manager.SelectedDocuments.set(docView, true); @@ -86,3 +83,9 @@ export namespace SelectionManager { } } + +Scripting.addGlobal(function selectDoc(doc: any) { + const view = DocumentManager.Instance.getDocumentView(doc); + view && SelectionManager.SelectDoc(view, false); + //Doc.UserDoc().activeSelection = new List([doc]); +});
\ No newline at end of file diff --git a/src/client/util/SettingsManager.scss b/src/client/util/SettingsManager.scss index 6513cb223..13c65042c 100644 --- a/src/client/util/SettingsManager.scss +++ b/src/client/util/SettingsManager.scss @@ -41,6 +41,7 @@ position: absolute; right: 1em; top: 1em; + cursor: pointer; } .settings-heading { @@ -133,4 +134,25 @@ } +} + +@media only screen and (max-device-width: 480px) { + .settings-interface { + width: 80vw; + height: 400px; + } + + .settings-interface .settings-body .settings-content input { + font-size: 30; + } + + .settings-interface button { + width: 100%; + font-size: 30px; + background: #b2cef8; + } + + .settings-interface .settings-heading { + font-size: 25; + } }
\ No newline at end of file diff --git a/src/client/util/SharingManager.scss b/src/client/util/SharingManager.scss index dec9f751a..fcbc05f8a 100644 --- a/src/client/util/SharingManager.scss +++ b/src/client/util/SharingManager.scss @@ -1,13 +1,75 @@ +@import "../views/globalCssVariables"; + .sharing-interface { display: flex; flex-direction: column; + width: 730px; + + .dialogue-box { + width: 450; + height: 300; + } + + .overlay { + transform: translate(-20px, -20px); + } + + .sharing-contents { + display: flex; + + button { + background: $darker-alt-accent; + outline: none; + border-radius: 5px; + border: 0px; + color: #fcfbf7; + text-transform: uppercase; + letter-spacing: 2px; + font-size: 75%; + padding: 0 10; + margin: 0 5; + transition: transform 0.2s; + height: 25; + } + + .individual-container, + .group-container { + width: 50%; + + .share-groups, + .share-individual { + margin-top: 20px; + margin-bottom: 20px; + } + + .groups-list, + .users-list { + font-style: italic; + background: white; + border: 1px solid black; + padding-left: 10px; + padding-right: 10px; + overflow-y: scroll; + overflow-x: hidden; + text-align: left; + display: flex; + align-content: center; + align-items: center; + text-align: center; + justify-content: center; + color: red; + height: 150px; + margin: 0 2; + } + } + } .focus-span { text-decoration: underline; } p { - font-size: 20px; + font-size: 15px; text-align: left; font-style: italic; padding: 0; @@ -36,33 +98,10 @@ } } - .share-individual { - margin-top: 20px; - margin-bottom: 20px; - } - - .users-list { - font-style: italic; - background: white; - border: 1px solid black; - padding-left: 10px; - padding-right: 10px; - max-height: 200px; - overflow: scroll; - height: -webkit-fill-available; - text-align: left; - display: flex; - align-content: center; - align-items: center; - text-align: center; - justify-content: center; - color: red; - } - .container { - display: block; + display: flex; position: relative; - margin-top: 10px; + margin-top: 5px; margin-bottom: 10px; font-size: 22px; -webkit-user-select: none; @@ -74,18 +113,27 @@ max-width: 700px; text-align: left; font-style: normal; - font-size: 15; + font-size: 14; font-weight: normal; padding: 0; + align-items: baseline; .padding { - padding: 0 0 0 20px; + padding: 0 10px 0 0; color: black; } .permissions-dropdown { outline: none; + height: 25; } + + .edit-actions { + display: flex; + position: absolute; + right: 51.5%; + } + } .no-users { diff --git a/src/client/util/SharingManager.tsx b/src/client/util/SharingManager.tsx index dc67145fc..127ee33ce 100644 --- a/src/client/util/SharingManager.tsx +++ b/src/client/util/SharingManager.tsx @@ -17,6 +17,8 @@ import { SelectionManager } from "./SelectionManager"; import { DocumentManager } from "./DocumentManager"; import { CollectionView } from "../views/collections/CollectionView"; import { DictationOverlay } from "../views/DictationOverlay"; +import GroupManager from "./GroupManager"; +import GroupMemberView from "./GroupMemberView"; library.add(fa.faCopy); @@ -28,17 +30,30 @@ export interface User { export enum SharingPermissions { None = "Not Shared", View = "Can View", - Comment = "Can Comment", + Add = "Can Add", Edit = "Can Edit" } const ColorMapping = new Map<string, string>([ [SharingPermissions.None, "red"], [SharingPermissions.View, "maroon"], - [SharingPermissions.Comment, "blue"], + [SharingPermissions.Add, "blue"], [SharingPermissions.Edit, "green"] ]); +const HierarchyMapping = new Map<string, string>([ + [SharingPermissions.None, "0"], + [SharingPermissions.View, "1"], + [SharingPermissions.Add, "2"], + [SharingPermissions.Edit, "3"], + + ["0", SharingPermissions.None], + ["1", SharingPermissions.View], + ["2", SharingPermissions.Add], + ["3", SharingPermissions.Edit] + +]); + const SharingKey = "sharingPermissions"; const PublicKey = "publicLinkPermissions"; const DefaultColor = "black"; @@ -55,11 +70,13 @@ export default class SharingManager extends React.Component<{}> { public static Instance: SharingManager; @observable private isOpen = false; @observable private users: ValidatedUser[] = []; + @observable private groups: Doc[] = []; @observable private targetDoc: Doc | undefined; @observable private targetDocView: DocumentView | undefined; @observable private copied = false; @observable private dialogueBoxOpacity = 1; @observable private overlayOpacity = 0.4; + @observable private groupToView: Opt<Doc>; private get linkVisible() { return this.sharingDoc ? this.sharingDoc[PublicKey] !== SharingPermissions.None : false; @@ -76,6 +93,8 @@ export default class SharingManager extends React.Component<{}> { this.sharingDoc = new Doc; } })); + + runInAction(() => this.groups = GroupManager.Instance.getAllGroupsCopy()); } public close = action(() => { @@ -121,26 +140,71 @@ export default class SharingManager extends React.Component<{}> { return Promise.all(evaluating); } - setInternalSharing = async (recipient: ValidatedUser, state: string) => { + setInternalGroupSharing = (group: Doc, permission: string) => { + const members: string[] = JSON.parse(StrCast(group.members)); + const users: ValidatedUser[] = this.users.filter(user => members.includes(user.user.email)); + + const sharingDoc = this.sharingDoc!; + if (permission === SharingPermissions.None) { + const metadata = sharingDoc[StrCast(group.groupName)]; + if (metadata) sharingDoc[StrCast(group.groupName)] = undefined; + } + else { + sharingDoc[StrCast(group.groupName)] = permission; + } + + users.forEach(user => { + this.setInternalSharing(user, permission, group); + }); + } + + setInternalSharing = async (recipient: ValidatedUser, state: string, group: Opt<Doc>) => { const { user, notificationDoc } = recipient; const target = this.targetDoc!; const manager = this.sharingDoc!; const key = user.userDocumentId; - if (state === SharingPermissions.None) { - const metadata = (await DocCastAsync(manager[key])); - if (metadata) { - const sharedAlias = (await DocCastAsync(metadata.sharedAlias))!; - Doc.RemoveDocFromList(notificationDoc, storage, sharedAlias); - manager[key] = undefined; - } - } else { - const sharedAlias = Doc.MakeAlias(target); - Doc.AddDocToList(notificationDoc, storage, sharedAlias); - const metadata = new Doc; - metadata.permissions = state; - metadata.sharedAlias = sharedAlias; - manager[key] = metadata; + + let metadata = await DocCastAsync(manager[key]); + const permissions: { [key: string]: number } = metadata?.permissions ? JSON.parse(StrCast(metadata.permissions)) : {}; + permissions[StrCast(group ? group.groupName : Doc.CurrentUserEmail)] = parseInt(HierarchyMapping.get(state)!); + const max = Math.max(...Object.values(permissions)); + + // let max = 0; + // const keys: string[] = []; + // for (const [key, value] of Object.entries(permissions)) { + // if (value === max && max !== 0) { + // keys.push(key); + // } + // else if (value > max) { + // keys.splice(0, keys.length); + // keys.push(key); + // max = value; + // } + // } + + switch (max) { + case 0: + if (metadata) { + const sharedAlias = (await DocCastAsync(metadata.sharedAlias))!; + Doc.RemoveDocFromList(notificationDoc, storage, sharedAlias); + manager[key] = undefined; + } + break; + + case 1: case 2: case 3: + if (!metadata) { + metadata = new Doc; + const sharedAlias = Doc.MakeAlias(target); + Doc.AddDocToList(notificationDoc, storage, sharedAlias); + metadata.sharedAlias = sharedAlias; + manager[key] = metadata; + } + metadata.permissions = JSON.stringify(permissions); + // metadata.usersShared = JSON.stringify(keys); + break; } + + if (metadata) metadata.maxPermission = HierarchyMapping.get(`${max}`); } private setExternalSharing = (state: string) => { @@ -211,17 +275,27 @@ export default class SharingManager extends React.Component<{}> { if (!sharingDoc) { return SharingPermissions.None; } - const metadata = sharingDoc[userKey] as Doc; + const metadata = sharingDoc[userKey] as Doc | string; if (!metadata) { return SharingPermissions.None; } - return StrCast(metadata.permissions, SharingPermissions.None); + return StrCast(metadata instanceof Doc ? metadata.maxPermission : metadata, SharingPermissions.None); } private get sharingInterface() { const existOtherUsers = this.users.length > 0; + const existGroups = this.groups.length > 0; + + // const manager = this.sharingDoc!; + return ( <div className={"sharing-interface"}> + {this.groupToView ? + <GroupMemberView + group={this.groupToView} + onCloseButtonClick={action(() => this.groupToView = undefined)} + /> : + null} <p className={"share-link"}>Manage the public link to {this.focusOn("this document...")}</p> {!this.linkVisible ? (null) : <div className={"link-container"}> @@ -252,31 +326,77 @@ export default class SharingManager extends React.Component<{}> { </select> </div> <div className={"hr-substitute"} /> - <p className={"share-individual"}>Privately share {this.focusOn("this document")} with an individual...</p> - <div className={"users-list"} style={{ display: existOtherUsers ? "block" : "flex", minHeight: existOtherUsers ? undefined : 200 }}> - {!existOtherUsers ? "There are no other users in your database." : - this.users.map(({ user, notificationDoc }) => { - const userKey = user.userDocumentId; - const permissions = this.computePermissions(userKey); - const color = ColorMapping.get(permissions); - return ( - <div - key={userKey} - className={"container"} - > - <select - className={"permissions-dropdown"} - value={permissions} - style={{ color, borderColor: color }} - onChange={e => this.setInternalSharing({ user, notificationDoc }, e.currentTarget.value)} - > - {this.sharingOptions} - </select> - <span className={"padding"}>{user.email}</span> - </div> - ); - }) - } + <div className="sharing-contents"> + <div className={"individual-container"}> + <p className={"share-individual"}>Privately share {this.focusOn("this document")} with an individual...</p> + <div className={"users-list"} style={{ display: existOtherUsers ? "block" : "flex", minHeight: existOtherUsers ? undefined : 150 }}>{/*200*/} + {!existOtherUsers ? "There are no other users in your database." : + this.users.map(({ user, notificationDoc }) => { // can't use async here + const userKey = user.userDocumentId; + const permissions = this.computePermissions(userKey); + const color = ColorMapping.get(permissions); + + // console.log(manager); + // const metadata = manager[userKey] as Doc; + // const usersShared = StrCast(metadata?.usersShared, ""); + // console.log(usersShared) + + + return ( + <div + key={userKey} + className={"container"} + > + <span className={"padding"}>{user.email}</span> + {/* <div className={"shared-by"}>{usersShared}</div> */} + <div className="edit-actions"> + <select + className={"permissions-dropdown"} + value={permissions} + style={{ color, borderColor: color }} + onChange={e => this.setInternalSharing({ user, notificationDoc }, e.currentTarget.value, undefined)} + > + {this.sharingOptions} + </select> + </div> + </div> + ); + }) + } + </div> + </div> + <div className={"group-container"}> + <p className={"share-groups"}>Privately share {this.focusOn("this document")} with a group...</p> + <div className={"groups-list"} style={{ display: existGroups ? "block" : "flex", minHeight: existOtherUsers ? undefined : 150 }}>{/*200*/} + {!existGroups ? "There are no groups in your database." : + this.groups.map(group => { + const permissions = this.computePermissions(StrCast(group.groupName)); + const color = ColorMapping.get(permissions); + return ( + <div + key={StrCast(group.groupName)} + className={"container"} + > + <span className={"padding"}>{group.groupName}</span> + <div className="edit-actions"> + <select + className={"permissions-dropdown"} + value={permissions} + style={{ color, borderColor: color }} + onChange={e => this.setInternalGroupSharing(group, e.currentTarget.value)} + > + {this.sharingOptions} + </select> + <button onClick={action(() => this.groupToView = group)}>Edit</button> + </div> + </div> + ); + }) + + } + + </div> + </div> </div> <div className={"close-button"} onClick={this.close}>Done</div> </div> @@ -284,6 +404,7 @@ export default class SharingManager extends React.Component<{}> { } render() { + // console.log(this.sharingDoc); return ( <MainViewModal contents={this.sharingInterface} diff --git a/src/client/views/.DS_Store b/src/client/views/.DS_Store Binary files differindex 5008ddfcf..3717a2923 100644 --- a/src/client/views/.DS_Store +++ b/src/client/views/.DS_Store diff --git a/src/client/views/AntimodeMenu.scss b/src/client/views/AntimodeMenu.scss index e56574bb7..be21cec12 100644 --- a/src/client/views/AntimodeMenu.scss +++ b/src/client/views/AntimodeMenu.scss @@ -42,4 +42,35 @@ background-repeat: no-repeat; background-position: left center; } +} + +@media only screen and (max-device-width: 480px) { + .antimodeMenu-cont { + height: 100px; + width: 100vw; + + &.with-rows { + flex-direction: column-reverse; + } + + .antimodeMenu-row { + display: flex; + height: 100%; + width: 100%; + } + + .antimodeMenu-button { + background-color: transparent; + width: 100px; + height: 100px; + + &.active { + background-color: #121212; + } + } + + .antimodeMenu-button:hover { + background-color: #121212; + } + } }
\ No newline at end of file diff --git a/src/client/views/AntimodeMenu.tsx b/src/client/views/AntimodeMenu.tsx index 3e4d20fea..cb293dee4 100644 --- a/src/client/views/AntimodeMenu.tsx +++ b/src/client/views/AntimodeMenu.tsx @@ -51,18 +51,15 @@ export default abstract class AntimodeMenu extends React.Component { if (this._opacity === 0.2) { this._transitionProperty = "opacity"; this._transitionDuration = "0.1s"; - this._transitionDelay = ""; - this._opacity = 0; - this._left = this._top = -300; } if (forceOut) { this._transitionProperty = ""; this._transitionDuration = ""; - this._transitionDelay = ""; - this._opacity = 0; - this._left = this._top = -300; } + this._transitionDelay = ""; + this._opacity = 0; + this._left = this._top = -300; } } @@ -131,7 +128,7 @@ export default abstract class AntimodeMenu extends React.Component { } protected getDragger = () => { - return <div className="antimodeMenu-dragger" onPointerDown={this.dragStart} style={{ width: "20px" }} />; + return <div className="antimodeMenu-dragger" key="dragger" onPointerDown={this.dragStart} style={{ width: "20px" }} />; } protected getElement(buttons: JSX.Element[]) { diff --git a/src/client/views/ContextMenu.tsx b/src/client/views/ContextMenu.tsx index 941d7b44a..07f7b8e6d 100644 --- a/src/client/views/ContextMenu.tsx +++ b/src/client/views/ContextMenu.tsx @@ -155,9 +155,11 @@ export class ContextMenu extends React.Component { @action closeMenu = () => { + const wasOpen = this._display; this.clearItems(); this._display = false; this._shouldDisplay = false; + return wasOpen; } @computed get filteredItems(): (OriginalMenuProps | string[])[] { diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx index fcaea0f0b..1667b2f65 100644 --- a/src/client/views/DocumentButtonBar.tsx +++ b/src/client/views/DocumentButtonBar.tsx @@ -271,7 +271,7 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV const considerPush = isText && this.considerGoogleDocsPush; return <div className="documentButtonBar"> <div className="documentButtonBar-button"> - <DocumentLinksButton View={this.view0!} AlwaysOn={true} /> + <DocumentLinksButton View={this.view0} AlwaysOn={true} InMenu={true} /> </div> <div className="documentButtonBar-button"> {this.templateButton} @@ -293,4 +293,4 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV </div> </div>; } -}
\ No newline at end of file +} diff --git a/src/client/views/DocumentDecorations.scss b/src/client/views/DocumentDecorations.scss index 11aaaaf8c..5948ada88 100644 --- a/src/client/views/DocumentDecorations.scss +++ b/src/client/views/DocumentDecorations.scss @@ -22,11 +22,20 @@ $linkGap : 3px; } + .documentDecorations-rotation { + pointer-events: auto; + // cursor: grabbing; + cursor: ns-resize; + width: 10px; + height: 10px; + } + .documentDecorations-resizer { pointer-events: auto; background: $alt-accent; opacity: 0.1; } + .documentDecorations-resizer:hover { opacity: 1; } @@ -87,14 +96,17 @@ $linkGap : 3px; background: unset; opacity: 1; } + #documentDecorations-topLeftResizer { - border-left: 2px solid; - border-top: solid 2px; + border-left: 2px solid; + border-top: solid 2px; } + #documentDecorations-bottomRightResizer { - border-right: 2px solid; - border-bottom: solid 2px; + border-right: 2px solid; + border-bottom: solid 2px; } + #documentDecorations-topLeftResizer:hover, #documentDecorations-bottomRightResizer:hover { opacity: 1; @@ -110,14 +122,17 @@ $linkGap : 3px; background: unset; opacity: 1; } + #documentDecorations-topRightResizer { - border-right: 2px solid; - border-top: 2px solid; + border-right: 2px solid; + border-top: 2px solid; } + #documentDecorations-bottomLeftResizer { - border-left: 2px solid; - border-bottom: 2px solid; + border-left: 2px solid; + border-bottom: 2px solid; } + #documentDecorations-topRightResizer:hover, #documentDecorations-bottomLeftResizer:hover { cursor: nesw-resize; @@ -139,10 +154,11 @@ $linkGap : 3px; width: 25px; height: calc(100% + 8px); // 8px for the height of the top resizer bar grid-column-start: 2; - grid-column-end : 2; + grid-column-end: 2; pointer-events: all; padding-left: 5px; } + .documentDecorations-title { opacity: 1; grid-column-start: 3; @@ -150,14 +166,16 @@ $linkGap : 3px; pointer-events: auto; overflow: hidden; text-align: center; - display: flex; + display: flex; border-bottom: solid 1px; - margin-left:10px; + margin-left: 10px; width: calc(100% - 10px); } + .focus-visible { - margin-left:0px; + margin-left: 0px; } + .publishBox { width: 20px; height: 22px; @@ -175,10 +193,10 @@ $linkGap : 3px; .documentDecorations-iconifyButton { opacity: 1; grid-column-start: 4; - grid-column-end: 6; + grid-column-end: 5; pointer-events: all; text-align: center; - left: -20px; + left: -25px; top: -2px; cursor: pointer; position: absolute; @@ -189,10 +207,13 @@ $linkGap : 3px; .documentDecorations-closeButton { opacity: 1; grid-column-start: 4; - grid-column-end: 6; + grid-column-end: 5; pointer-events: all; text-align: center; cursor: pointer; + width: 15px; + margin-left: -8px; + margin-top: auto; } .documentDecorations-minimizeButton { @@ -208,8 +229,9 @@ $linkGap : 3px; width: 8px; height: $MINIMIZED_ICON_SIZE; max-height: 20px; - > svg { - margin:0; + + >svg { + margin: 0; } } @@ -348,7 +370,8 @@ $linkGap : 3px; padding: 2px 12px; list-style: none; - .templateToggle, .chromeToggle { + .templateToggle, + .chromeToggle { text-align: left; } diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index d7b0ab7a9..a45ef8862 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -1,5 +1,5 @@ import { IconProp, library } from '@fortawesome/fontawesome-svg-core'; -import { faCaretUp, faFilePdf, faFilm, faImage, faObjectGroup, faStickyNote, faTextHeight, faArrowAltCircleDown, faArrowAltCircleUp, faCheckCircle, faCloudUploadAlt, faLink, faShare, faStopCircle, faSyncAlt, faTag, faTimes } from '@fortawesome/free-solid-svg-icons'; +import { faCaretUp, faFilePdf, faFilm, faImage, faObjectGroup, faStickyNote, faTextHeight, faArrowAltCircleDown, faArrowAltCircleUp, faCheckCircle, faCloudUploadAlt, faLink, faShare, faStopCircle, faSyncAlt, faTag, faTimes, faAngleLeft, faAngleRight, faAngleDoubleLeft, faAngleDoubleRight, faPause } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { action, computed, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; @@ -17,11 +17,14 @@ import { DocumentButtonBar } from './DocumentButtonBar'; import './DocumentDecorations.scss'; import { DocumentView } from "./nodes/DocumentView"; import React = require("react"); -import { Id } from '../../fields/FieldSymbols'; +import { Id, Copy, Update } from '../../fields/FieldSymbols'; import e = require('express'); import { CollectionDockingView } from './collections/CollectionDockingView'; import { SnappingManager } from '../util/SnappingManager'; import { HtmlField } from '../../fields/HtmlField'; +import { InkData, InkField, InkTool } from "../../fields/InkField"; +import { update } from 'serializr'; +import { Transform } from "../util/Transform"; library.add(faCaretUp); library.add(faObjectGroup); @@ -38,6 +41,11 @@ library.add(faCheckCircle); library.add(faCloudUploadAlt); library.add(faSyncAlt); library.add(faShare); +library.add(faAngleDoubleLeft); +library.add(faAngleDoubleRight); +library.add(faAngleLeft); +library.add(faAngleRight); +library.add(faPause); @observer export class DocumentDecorations extends React.Component<{}, { value: string }> { @@ -50,6 +58,10 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> private _resizeUndo?: UndoManager.Batch; private _offX = 0; _offY = 0; // offset from click pt to inner edge of resize border private _snapX = 0; _snapY = 0; // last snapped location of resize border + private _prevX = 0; + private _prevY = 0; + private _centerPoints: { X: number, Y: number }[] = []; + @observable private _accumulatedTitle = ""; @observable private _titleControlString: string = "#title"; @observable private _edtingTitle = false; @@ -70,7 +82,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> get Bounds(): { x: number, y: number, b: number, r: number } { return SelectionManager.SelectedDocuments().reduce((bounds, documentView) => { if (documentView.props.renderDepth === 0 || - documentView.props.treeViewId || + documentView.props.treeViewDoc || Doc.AreProtosEqual(documentView.props.Document, Doc.UserDoc())) { return bounds; } @@ -238,6 +250,82 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> return false; } + @action + onRotateDown = (e: React.PointerEvent): void => { + setupMoveUpEvents(this, e, this.onRotateMove, this.onRotateUp, (e) => { }); + this._prevX = e.clientX; + this._prevY = e.clientY; + SelectionManager.SelectedDocuments().forEach(action((element: DocumentView) => { + const doc = Document(element.rootDoc); + if (doc.type === DocumentType.INK && doc.x && doc.y && doc._width && doc._height && doc.data) { + const ink = Cast(doc.data, InkField)?.inkData; + if (ink) { + const xs = ink.map(p => p.X); + const ys = ink.map(p => p.Y); + const left = Math.min(...xs); + const top = Math.min(...ys); + const right = Math.max(...xs); + const bottom = Math.max(...ys); + // this._centerPoints.push({ X: ((right - left) / 2) + left, Y: ((bottom - top) / 2) + bottom }); + this._centerPoints.push({ X: left, Y: top }); + } + } + })); + + } + @action + onRotateMove = (e: PointerEvent, down: number[]): boolean => { + + // const distance = Math.sqrt((this._prevY - e.clientY) * (this._prevY - e.clientY) + (this._prevX - e.clientX) * (this._prevX - e.clientX)); + const distance = Math.abs(this._prevY - e.clientY); + var angle = 0; + //think of a better condition later... + // if ((down[0] < e.clientX && this._prevY < e.clientY) || (down[0] > e.clientX && this._prevY > e.clientY)) { + if (e.clientY > this._prevY) { + angle = distance * (Math.PI / 180); + // } else if ((down[0] < e.clientX && this._prevY > e.clientY) || (down[0] > e.clientX && this._prevY <= e.clientY)) { + } else if (e.clientY < this._prevY) { + angle = - distance * (Math.PI / 180); + } + this._prevX = e.clientX; + this._prevY = e.clientY; + var index = 0; + SelectionManager.SelectedDocuments().forEach(action((element: DocumentView) => { + const doc = Document(element.rootDoc); + if (doc.type === DocumentType.INK && doc.x && doc.y && doc._width && doc._height && doc.data) { + const ink = Cast(doc.data, InkField)?.inkData; + if (ink) { + + const newPoints: { X: number, Y: number }[] = []; + for (var i = 0; i < ink.length; i++) { + const newX = Math.cos(angle) * (ink[i].X - this._centerPoints[index].X) - Math.sin(angle) * (ink[i].Y - this._centerPoints[index].Y) + this._centerPoints[index].X; + const newY = Math.sin(angle) * (ink[i].X - this._centerPoints[index].X) + Math.cos(angle) * (ink[i].Y - this._centerPoints[index].Y) + this._centerPoints[index].Y; + newPoints.push({ X: newX, Y: newY }); + } + doc.data = new InkField(newPoints); + const xs = newPoints.map(p => p.X); + const ys = newPoints.map(p => p.Y); + const left = Math.min(...xs); + const top = Math.min(...ys); + const right = Math.max(...xs); + const bottom = Math.max(...ys); + + doc._height = (bottom - top) * element.props.ScreenToLocalTransform().Scale; + doc._width = (right - left) * element.props.ScreenToLocalTransform().Scale; + + } + index++; + } + })); + return false; + } + + onRotateUp = (e: PointerEvent) => { + this._centerPoints = []; + } + + + _initialAutoHeight = false; _dragHeights = new Map<Doc, number>(); @action @@ -512,49 +600,54 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> zIndex: SelectionManager.SelectedDocuments().length > 1 ? 900 : 0, }} onPointerDown={this.onBackgroundDown} onContextMenu={e => { e.preventDefault(); e.stopPropagation(); }} > </div> - <div className="documentDecorations-container" ref={this.setTextBar} style={{ - width: (bounds.r - bounds.x + this._resizeBorderWidth) + "px", - height: (bounds.b - bounds.y + this._resizeBorderWidth + this._titleHeight) + "px", - left: bounds.x - this._resizeBorderWidth / 2, - top: bounds.y - this._resizeBorderWidth / 2 - this._titleHeight, - }}> - {maximizeIcon} - {titleArea} - <div className="documentDecorations-iconifyButton" title={`${seldoc.finalLayoutKey.includes("icon") ? "De" : ""}Iconify Document`} onPointerDown={this.onIconifyDown}> - {"_"} - </div> - <div className="documentDecorations-closeButton" title="Open Document in Tab" onPointerDown={this.onMaximizeDown}> - {SelectionManager.SelectedDocuments().length === 1 ? DocumentDecorations.DocumentIcon(StrCast(seldoc.props.Document.layout, "...")) : "..."} + {bounds.r - bounds.x < 15 && bounds.b - bounds.y < 15 ? (null) : <> + <div className="documentDecorations-container" key="container" ref={this.setTextBar} style={{ + width: (bounds.r - bounds.x + this._resizeBorderWidth) + "px", + height: (bounds.b - bounds.y + this._resizeBorderWidth + this._titleHeight) + "px", + left: bounds.x - this._resizeBorderWidth / 2, + top: bounds.y - this._resizeBorderWidth / 2 - this._titleHeight, + }}> + {maximizeIcon} + {titleArea} + {SelectionManager.SelectedDocuments().length !== 1 || seldoc.Document.type === DocumentType.INK ? (null) : + <div className="documentDecorations-iconifyButton" title={`${seldoc.finalLayoutKey.includes("icon") ? "De" : ""}Iconify Document`} onPointerDown={this.onIconifyDown}> + {"_"} + </div>} + <div className="documentDecorations-closeButton" title="Open Document in Tab" onPointerDown={this.onMaximizeDown}> + {SelectionManager.SelectedDocuments().length === 1 ? DocumentDecorations.DocumentIcon(StrCast(seldoc.props.Document.layout, "...")) : "..."} + </div> + <div id="documentDecorations-rotation" className="documentDecorations-rotation" + onPointerDown={this.onRotateDown}> ⟲ </div> + <div id="documentDecorations-topLeftResizer" className="documentDecorations-resizer" + onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}></div> + <div id="documentDecorations-topResizer" className="documentDecorations-resizer" + onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}></div> + <div id="documentDecorations-topRightResizer" className="documentDecorations-resizer" + onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}></div> + <div id="documentDecorations-leftResizer" className="documentDecorations-resizer" + onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}></div> + <div id="documentDecorations-centerCont"></div> + <div id="documentDecorations-rightResizer" className="documentDecorations-resizer" + onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}></div> + <div id="documentDecorations-bottomLeftResizer" className="documentDecorations-resizer" + onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}></div> + <div id="documentDecorations-bottomResizer" className="documentDecorations-resizer" + onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}></div> + <div id="documentDecorations-bottomRightResizer" className="documentDecorations-resizer" + onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}></div> + {seldoc.props.renderDepth <= 1 || !seldoc.props.ContainingCollectionView ? (null) : + <div id="documentDecorations-levelSelector" className="documentDecorations-selector" + title="tap to select containing document" onPointerDown={this.onSelectorUp} onContextMenu={e => e.preventDefault()}> + <FontAwesomeIcon className="documentdecorations-times" icon={faArrowAltCircleUp} size="lg" /> + </div>} + <div id="documentDecorations-borderRadius" className="documentDecorations-radius" + onPointerDown={this.onRadiusDown} onContextMenu={(e) => e.preventDefault()}></div> + + </div > + <div className="link-button-container" key="links" style={{ left: bounds.x - this._resizeBorderWidth / 2 + 10, top: bounds.b + this._resizeBorderWidth / 2 }}> + <DocumentButtonBar views={SelectionManager.SelectedDocuments} /> </div> - <div id="documentDecorations-topLeftResizer" className="documentDecorations-resizer" - onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}></div> - <div id="documentDecorations-topResizer" className="documentDecorations-resizer" - onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}></div> - <div id="documentDecorations-topRightResizer" className="documentDecorations-resizer" - onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}></div> - <div id="documentDecorations-leftResizer" className="documentDecorations-resizer" - onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}></div> - <div id="documentDecorations-centerCont"></div> - <div id="documentDecorations-rightResizer" className="documentDecorations-resizer" - onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}></div> - <div id="documentDecorations-bottomLeftResizer" className="documentDecorations-resizer" - onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}></div> - <div id="documentDecorations-bottomResizer" className="documentDecorations-resizer" - onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}></div> - <div id="documentDecorations-bottomRightResizer" className="documentDecorations-resizer" - onPointerDown={this.onPointerDown} onContextMenu={(e) => e.preventDefault()}></div> - {seldoc.props.renderDepth <= 1 || !seldoc.props.ContainingCollectionView ? (null) : - <div id="documentDecorations-levelSelector" className="documentDecorations-selector" - title="tap to select containing document" onPointerDown={this.onSelectorUp} onContextMenu={e => e.preventDefault()}> - <FontAwesomeIcon className="documentdecorations-times" icon={faArrowAltCircleUp} size="lg" /> - </div>} - <div id="documentDecorations-borderRadius" className="documentDecorations-radius" - onPointerDown={this.onRadiusDown} onContextMenu={(e) => e.preventDefault()}></div> - - </div > - <div className="link-button-container" style={{ left: bounds.x - this._resizeBorderWidth / 2 + 10, top: bounds.b + this._resizeBorderWidth / 2 }}> - <DocumentButtonBar views={SelectionManager.SelectedDocuments} /> - </div> + </>} </div > ); } diff --git a/src/client/views/EditableView.tsx b/src/client/views/EditableView.tsx index ee3ce1cf3..628db366f 100644 --- a/src/client/views/EditableView.tsx +++ b/src/client/views/EditableView.tsx @@ -31,6 +31,7 @@ export interface EditableProps { fontStyle?: string; fontSize?: number; height?: number | "auto"; + sizeToContent?: boolean; maxHeight?: number; display?: string; autosuggestProps?: { @@ -60,13 +61,11 @@ export interface EditableProps { */ @observer export class EditableView extends React.Component<EditableProps> { - public static loadId = ""; @observable _editing: boolean = false; constructor(props: EditableProps) { super(props); this._editing = this.props.editing ? true : false; - EditableView.loadId = ""; } // @action @@ -150,37 +149,44 @@ export class EditableView extends React.Component<EditableProps> { @action setIsFocused = (value: boolean) => { const wasFocused = this._editing; - this._editing = value; + //this._editing = value; return wasFocused !== this._editing; } _ref = React.createRef<HTMLDivElement>(); + renderEditor() { + return this.props.autosuggestProps + ? <Autosuggest + {...this.props.autosuggestProps.autosuggestProps} + inputProps={{ + className: "editableView-input", + onKeyDown: this.onKeyDown, + autoFocus: true, + onBlur: e => this.finalizeEdit(e.currentTarget.value, false, true), + onPointerDown: this.stopPropagation, + onClick: this.stopPropagation, + onPointerUp: this.stopPropagation, + value: this.props.autosuggestProps.value, + onChange: this.props.autosuggestProps.onChange + }} + /> + : <input className="editableView-input" + defaultValue={this.props.GetValue()} + onKeyDown={this.onKeyDown} + autoFocus={true} + onBlur={e => this.finalizeEdit(e.currentTarget.value, false, true)} + onPointerDown={this.stopPropagation} onClick={this.stopPropagation} onPointerUp={this.stopPropagation} + style={{ display: this.props.display, fontSize: this.props.fontSize, minWidth: 20 }} + placeholder={this.props.placeholder} + />; + } render() { if (this._editing && this.props.GetValue() !== undefined) { - return this.props.autosuggestProps - ? <Autosuggest - {...this.props.autosuggestProps.autosuggestProps} - inputProps={{ - className: "editableView-input", - onKeyDown: this.onKeyDown, - autoFocus: true, - onBlur: e => this.finalizeEdit(e.currentTarget.value, false, true), - onPointerDown: this.stopPropagation, - onClick: this.stopPropagation, - onPointerUp: this.stopPropagation, - value: this.props.autosuggestProps.value, - onChange: this.props.autosuggestProps.onChange - }} - /> - : <input className="editableView-input" - defaultValue={this.props.GetValue()} - onKeyDown={this.onKeyDown} - autoFocus={true} - onBlur={e => this.finalizeEdit(e.currentTarget.value, false, true)} - onPointerDown={this.stopPropagation} onClick={this.stopPropagation} onPointerUp={this.stopPropagation} - style={{ display: this.props.display, fontSize: this.props.fontSize }} - placeholder={this.props.placeholder} - />; + return this.props.sizeToContent ? + <div style={{ display: "grid", minWidth: 100 }}> + <div style={{ display: "inline-block", position: "relative", height: 0, width: "100%", overflow: "hidden" }}>{this.props.GetValue()}</div> + {this.renderEditor()} + </div> : this.renderEditor(); } else { this.props.autosuggestProps?.resetValue(); return (this.props.contents instanceof ObjectField ? (null) : @@ -188,7 +194,6 @@ export class EditableView extends React.Component<EditableProps> { ref={this._ref} style={{ display: this.props.display, minHeight: "20px", height: `${this.props.height ? this.props.height : "auto"}`, maxHeight: `${this.props.maxHeight}` }} onClick={this.onClick} placeholder={this.props.placeholder}> - <span style={{ fontStyle: this.props.fontStyle, fontSize: this.props.fontSize, color: this.props.contents ? "black" : "grey" }}>{this.props.contents ? this.props.contents?.valueOf() : this.props.placeholder?.valueOf()}</span> </div> ); diff --git a/src/client/views/GestureOverlay.scss b/src/client/views/GestureOverlay.scss index 107077792..f61f4a05e 100644 --- a/src/client/views/GestureOverlay.scss +++ b/src/client/views/GestureOverlay.scss @@ -1,7 +1,7 @@ .gestureOverlay-cont { width: 100vw; height: 100vh; - position: absolute; + position: fixed; top: 0; left: 0; touch-action: none; diff --git a/src/client/views/GestureOverlay.tsx b/src/client/views/GestureOverlay.tsx index aeac1d4a9..487467b2b 100644 --- a/src/client/views/GestureOverlay.tsx +++ b/src/client/views/GestureOverlay.tsx @@ -5,7 +5,6 @@ import { Doc } from "../../fields/Doc"; import { InkData, InkTool } from "../../fields/InkField"; import { Cast, FieldValue, NumCast } from "../../fields/Types"; import MobileInkOverlay from "../../mobile/MobileInkOverlay"; -import MobileInterface from "../../mobile/MobileInterface"; import { GestureUtils } from "../../pen-gestures/GestureUtils"; import { MobileInkOverlayContent } from "../../server/Message"; import { emptyFunction, emptyPath, returnEmptyString, returnFalse, returnOne, returnTrue, returnZero, returnEmptyFilter } from "../../Utils"; @@ -18,12 +17,13 @@ import { LinkManager } from "../util/LinkManager"; import { Scripting } from "../util/Scripting"; import { Transform } from "../util/Transform"; import "./GestureOverlay.scss"; -import { ActiveInkBezierApprox, ActiveInkColor, ActiveInkWidth, InkingStroke, SetActiveInkColor, SetActiveInkWidth } from "./InkingStroke"; +import { ActiveInkBezierApprox, ActiveArrowStart, ActiveArrowEnd, ActiveFillColor, ActiveInkColor, ActiveInkWidth, InkingStroke, SetActiveInkColor, SetActiveInkWidth, SetActiveFillColor, SetActiveArrowStart, SetActiveArrowEnd, ActiveDash, SetActiveDash } from "./InkingStroke"; import { DocumentView } from "./nodes/DocumentView"; import { RadialMenu } from "./nodes/RadialMenu"; import HorizontalPalette from "./Palette"; import { Touchable } from "./Touchable"; import TouchScrollableMenu, { TouchScrollableMenuItem } from "./TouchScrollableMenu"; +import HeightLabel from "./collections/collectionMulticolumn/MultirowHeightLabel"; @observer export default class GestureOverlay extends Touchable { @@ -32,6 +32,10 @@ export default class GestureOverlay extends Touchable { @observable public InkShape: string = ""; @observable public SavedColor?: string; @observable public SavedWidth?: string; + @observable public SavedFill?: string; + @observable public SavedArrowStart: string = "none"; + @observable public SavedArrowEnd: string = "none"; + @observable public SavedDash: String = "0"; @observable public Tool: ToolglassTools = ToolglassTools.None; @observable private _thumbX?: number; @@ -107,7 +111,7 @@ export default class GestureOverlay extends Touchable { onReactTouchStart = (te: React.TouchEvent) => { document.removeEventListener("touchmove", this.onReactHoldTouchMove); document.removeEventListener("touchend", this.onReactHoldTouchEnd); - if (RadialMenu.Instance._display === true) { + if (RadialMenu.Instance?._display === true) { te.preventDefault(); te.stopPropagation(); RadialMenu.Instance.closeMenu(); @@ -157,8 +161,8 @@ export default class GestureOverlay extends Touchable { // -- radial menu code -- this._holdTimer = setTimeout(() => { console.log("hold"); - const target = document.elementFromPoint(te.changedTouches.item(0).clientX, te.changedTouches.item(0).clientY); - const pt: any = te.touches[te.touches.length - 1]; + const target = document.elementFromPoint(te.changedTouches?.item(0).clientX, te.changedTouches?.item(0).clientY); + const pt: any = te.touches[te.touches?.length - 1]; if (nts.nt.length === 1 && pt.radiusX > 1 && pt.radiusY > 1) { target?.dispatchEvent( new CustomEvent<InteractionUtils.MultiTouchEvent<React.TouchEvent>>("dashOnTouchHoldStart", @@ -575,14 +579,6 @@ export default class GestureOverlay extends Touchable { const points = this._points.map(p => ({ X: p.X - B.left, Y: p.Y - B.top })); //push first points to so interactionUtil knows pointer is up this._points.push({ X: this._points[0].X, Y: this._points[0].Y }); - if (MobileInterface.Instance && MobileInterface.Instance.drawingInk) { - DocServer.Mobile.dispatchGesturePoints({ - points: this._points, - bounds: B, - color: ActiveInkColor(), - width: ActiveInkWidth() - }); - } const initialPoint = this._points[0.]; const xInGlass = initialPoint.X > (this._thumbX ?? Number.MAX_SAFE_INTEGER) && initialPoint.X < (this._thumbX ?? Number.MAX_SAFE_INTEGER) + (this.height); @@ -627,7 +623,9 @@ export default class GestureOverlay extends Touchable { this.makePolygon(this.InkShape, false); this.dispatchGesture(GestureUtils.Gestures.Stroke); this._points = []; - this.InkShape = ""; + if (this.InkShape !== "noRec") { + this.InkShape = ""; + } } // if we're not drawing in a toolglass try to recognize as gesture else { @@ -677,6 +675,10 @@ export default class GestureOverlay extends Touchable { } else { this._points = []; } + SetActiveArrowStart("none"); + GestureOverlay.Instance.SavedArrowStart = ActiveArrowStart(); + SetActiveArrowEnd("none"); + GestureOverlay.Instance.SavedArrowEnd = ActiveArrowEnd(); document.removeEventListener("pointermove", this.onPointerMove); document.removeEventListener("pointerup", this.onPointerUp); } @@ -688,7 +690,9 @@ export default class GestureOverlay extends Touchable { var left = Math.min(...xs); var bottom = Math.max(...ys); var top = Math.min(...ys); - + if (shape === "noRec") { + return; + } if (!gesture) { //if shape options is activated in inkOptionMenu //take second to last point because _point[length-1] is _points[0] @@ -712,7 +716,7 @@ export default class GestureOverlay extends Touchable { this._points = []; switch (shape) { //must push an extra point in the end so InteractionUtils knows pointer is up. - //must be (points[0].X,points[0]-1) + //must be (points[0].X,points[0]-1) case "rectangle": this._points.push({ X: left, Y: top }); this._points.push({ X: right, Y: top }); @@ -747,7 +751,7 @@ export default class GestureOverlay extends Touchable { case "line": this._points.push({ X: left, Y: top }); this._points.push({ X: right, Y: bottom }); - this._points.push({ X: right, Y: bottom - 1 }); + // this._points.push({ X: right, Y: bottom - 1 }); break; case "arrow": const x1 = left; @@ -766,7 +770,7 @@ export default class GestureOverlay extends Touchable { this._points.push({ X: x3, Y: y3 }); this._points.push({ X: x4, Y: y4 }); this._points.push({ X: x2, Y: y2 }); - this._points.push({ X: x1, Y: y1 - 1 }); + // this._points.push({ X: x1, Y: y1 - 1 }); } } @@ -802,19 +806,28 @@ export default class GestureOverlay extends Touchable { } @computed get elements() { - const B = this.svgBounds; const width = Number(ActiveInkWidth()); + const B = this.svgBounds; + B.left = B.left - width / 2; + B.right = B.right + width / 2; + B.top = B.top - width / 2; + B.bottom = B.bottom + width / 2; + B.width += width; + B.height += width; return [ this.props.children, this._palette, [this._strokes.map((l, i) => { const b = this.getBounds(l); return <svg key={i} 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(), width, width, ActiveInkBezierApprox(), 1, 1, this.InkShape, "none", false)} + {InteractionUtils.CreatePolyline(l, b.left, b.top, ActiveInkColor(), width, width, + ActiveInkBezierApprox(), ActiveFillColor(), ActiveArrowStart(), ActiveArrowEnd(), + ActiveDash(), 1, 1, this.InkShape, "none", false, false)} </svg>; }), - this._points.length <= 1 ? (null) : <svg key="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(), width, width, ActiveInkBezierApprox(), 1, 1, this.InkShape, "none", false)} + this._points.length <= 1 ? (null) : <svg key="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(), width, width, ActiveInkBezierApprox(), ActiveFillColor(), ActiveArrowStart(), ActiveArrowEnd(), ActiveDash(), 1, 1, this.InkShape, "none", false, false)} </svg>] ]; } @@ -890,7 +903,7 @@ export default class GestureOverlay extends Touchable { } } -// export class +// export class export enum ToolglassTools { InkToText = "inktotext", @@ -903,12 +916,20 @@ Scripting.addGlobal("GestureOverlay", GestureOverlay); Scripting.addGlobal(function setToolglass(tool: any) { runInAction(() => GestureOverlay.Instance.Tool = tool); }); -Scripting.addGlobal(function setPen(width: any, color: any) { +Scripting.addGlobal(function setPen(width: any, color: any, fill: any, arrowStart: any, arrowEnd: any, dash: any) { runInAction(() => { GestureOverlay.Instance.SavedColor = ActiveInkColor(); SetActiveInkColor(color); GestureOverlay.Instance.SavedWidth = ActiveInkWidth(); SetActiveInkWidth(width); + GestureOverlay.Instance.SavedFill = ActiveFillColor(); + SetActiveFillColor(fill); + GestureOverlay.Instance.SavedArrowStart = ActiveArrowStart(); + SetActiveArrowStart(arrowStart); + GestureOverlay.Instance.SavedArrowEnd = ActiveArrowEnd(); + SetActiveArrowStart(arrowEnd); + GestureOverlay.Instance.SavedDash = ActiveDash(); + SetActiveDash(dash); }); }); Scripting.addGlobal(function resetPen() { @@ -919,4 +940,4 @@ Scripting.addGlobal(function resetPen() { }, "resets the pen tool"); Scripting.addGlobal(function createText(text: any, x: any, y: any) { GestureOverlay.Instance.dispatchGesture("text", [{ X: x, Y: y }], text); -}, "creates a text document with inputted text and coordinates", "(text: any, x: any, y: any)");
\ No newline at end of file +}, "creates a text document with inputted text and coordinates", "(text: any, x: any, y: any)"); diff --git a/src/client/views/GlobalKeyHandler.ts b/src/client/views/GlobalKeyHandler.ts index 7bc8cf6a7..34f666f62 100644 --- a/src/client/views/GlobalKeyHandler.ts +++ b/src/client/views/GlobalKeyHandler.ts @@ -15,11 +15,12 @@ import { SelectionManager } from "../util/SelectionManager"; import SharingManager from "../util/SharingManager"; import { undoBatch, UndoManager } from "../util/UndoManager"; import { CollectionDockingView } from "./collections/CollectionDockingView"; -import { MarqueeView } from "./collections/collectionFreeForm/MarqueeView"; import { DocumentDecorations } from "./DocumentDecorations"; import { MainView } from "./MainView"; import { DocumentView } from "./nodes/DocumentView"; import { DocumentLinksButton } from "./nodes/DocumentLinksButton"; +import PDFMenu from "./pdf/PDFMenu"; +import { ContextMenu } from "./ContextMenu"; const modifiers = ["control", "meta", "shift", "alt"]; type KeyHandler = (keycode: string, e: KeyboardEvent) => KeyControlInfo | Promise<KeyControlInfo>; @@ -78,19 +79,28 @@ export default class KeyManager { // MarqueeView.DragMarquee = !MarqueeView.DragMarquee; // bcz: this needs a better disclosure UI break; case "escape": + // if (DocumentLinksButton.StartLink) { + // if (DocumentLinksButton.StartLink.Document) { + // action((e: React.PointerEvent<HTMLDivElement>) => { + // Doc.UnBrushDoc(DocumentLinksButton.StartLink?.Document as Doc); + // }); + // } + // } DocumentLinksButton.StartLink = undefined; + const main = MainView.Instance; Doc.SetSelectedTool(InkTool.None); + var doDeselect = true; if (main.isPointerDown) { DragManager.AbortDrag(); } else { if (CollectionDockingView.Instance.HasFullScreen()) { CollectionDockingView.Instance.CloseFullScreen(); } else { - SelectionManager.DeselectAll(); + doDeselect = !ContextMenu.Instance.closeMenu(); } } - SelectionManager.DeselectAll(); + doDeselect && SelectionManager.DeselectAll(); DictationManager.Controls.stop(); // RecommendationsBox.Instance.closeMenu(); GoogleAuthenticationManager.Instance.cancel(); @@ -264,7 +274,7 @@ export default class KeyManager { } break; case "c": - if (DocumentDecorations.Instance.Bounds.r - DocumentDecorations.Instance.Bounds.x > 2) { + if (!PDFMenu.Instance.Active && DocumentDecorations.Instance.Bounds.r - DocumentDecorations.Instance.Bounds.x > 2) { const bds = DocumentDecorations.Instance.Bounds; const pt = SelectionManager.SelectedDocuments()[0].props.ScreenToLocalTransform().transformPoint(bds.x + (bds.r - bds.x) / 2, bds.y + (bds.b - bds.y) / 2); const text = `__DashCloneId(${pt?.[0] || 0},${pt?.[1] || 0}):` + SelectionManager.SelectedDocuments().map(dv => dv.Document[Id]).join(":"); @@ -333,4 +343,4 @@ export default class KeyManager { }; }); -}
\ No newline at end of file +} diff --git a/src/client/views/InkingStroke.scss b/src/client/views/InkingStroke.scss index 433433a42..30ab1967e 100644 --- a/src/client/views/InkingStroke.scss +++ b/src/client/views/InkingStroke.scss @@ -4,4 +4,8 @@ stroke-linecap: round; overflow: visible !important; transform-origin: top left; + + svg:not(:root) { + overflow: visible !important; + } }
\ No newline at end of file diff --git a/src/client/views/InkingStroke.tsx b/src/client/views/InkingStroke.tsx index cdabd213b..7d6e7e5dd 100644 --- a/src/client/views/InkingStroke.tsx +++ b/src/client/views/InkingStroke.tsx @@ -4,7 +4,7 @@ import { observer } from "mobx-react"; import { documentSchema } from "../../fields/documentSchemas"; import { InkData, InkField, InkTool } from "../../fields/InkField"; import { makeInterface } from "../../fields/Schema"; -import { Cast, StrCast, BoolCast } from "../../fields/Types"; +import { Cast, StrCast } from "../../fields/Types"; import { TraceMobx } from "../../fields/util"; import { CognitiveServices } from "../cognitive_services/CognitiveServices"; import { InteractionUtils } from "../util/InteractionUtils"; @@ -54,10 +54,13 @@ export class InkingStroke extends ViewBoxBaseComponent<FieldViewProps, InkDocume const scaleY = (this.props.PanelHeight() - strokeWidth) / (height - strokeWidth); const strokeColor = StrCast(this.layoutDoc.color, ActiveInkColor()); const points = InteractionUtils.CreatePolyline(data, left, top, strokeColor, strokeWidth, strokeWidth, - StrCast(this.layoutDoc.strokeBezier, ActiveInkBezierApprox()), scaleX, scaleY, "", "none", (this.props.isSelected() || BoolCast(this.props.backgroundHalo?.())) && strokeWidth <= 5); + StrCast(this.layoutDoc.strokeBezier, ActiveInkBezierApprox()), StrCast(this.layoutDoc.fillColor, ActiveFillColor()), + StrCast(this.layoutDoc.arrowStart, ActiveArrowStart()), StrCast(this.layoutDoc.arrowEnd, ActiveArrowEnd()), + StrCast(this.layoutDoc.dash, ActiveDash()), scaleX, scaleY, "", "none", this.props.isSelected() && strokeWidth <= 5, false); const hpoints = InteractionUtils.CreatePolyline(data, left, top, this.props.isSelected() && strokeWidth > 5 ? strokeColor : "transparent", strokeWidth, (strokeWidth + 15), - StrCast(this.layoutDoc.strokeBezier, ActiveInkBezierApprox()), scaleX, scaleY, "", this.props.active() ? "visiblestroke" : "none", false); + StrCast(this.layoutDoc.strokeBezier, ActiveInkBezierApprox()), StrCast(this.layoutDoc.fillColor, ActiveFillColor()), + "none", "none", "0", scaleX, scaleY, "", this.props.active() ? "visiblepainted" : "none", false, true); return ( <svg className="inkingStroke" width={width} @@ -65,29 +68,14 @@ export class InkingStroke extends ViewBoxBaseComponent<FieldViewProps, InkDocume style={{ pointerEvents: this.props.Document.isInkMask ? "all" : "none", transform: this.props.Document.isInkMask ? "translate(2500px, 2500px)" : undefined, - mixBlendMode: this.layoutDoc.tool === InkTool.Highlighter ? "multiply" : "unset" + mixBlendMode: this.layoutDoc.tool === InkTool.Highlighter ? "multiply" : "unset", + overflow: "visible", }} onContextMenu={() => { - ContextMenu.Instance.addItem({ description: "Analyze Stroke", event: this.analyzeStrokes, icon: "paint-brush" }); - ContextMenu.Instance.addItem({ description: "Make Mask", event: this.makeMask, icon: "paint-brush" }); + ContextMenu.Instance?.addItem({ description: "Analyze Stroke", event: this.analyzeStrokes, icon: "paint-brush" }); + ContextMenu.Instance?.addItem({ description: "Make Mask", event: this.makeMask, icon: "paint-brush" }); }} ><defs> - <filter id="dangerShine"> - <feColorMatrix type="matrix" - result="color" - values="1 0 0 0 0 - 0 0 0 0 0 - 0 0 0 0 0 - 0 0 0 1 0"> - </feColorMatrix> - <feGaussianBlur in="color" stdDeviation="4" result="blur"></feGaussianBlur> - <feOffset in="blur" dx="0" dy="0" result="offset"></feOffset> - <feMerge> - <feMergeNode in="bg"></feMergeNode> - <feMergeNode in="offset"></feMergeNode> - <feMergeNode in="SourceGraphic"></feMergeNode> - </feMerge> - </filter> </defs> {hpoints} {points} @@ -100,17 +88,33 @@ export class InkingStroke extends ViewBoxBaseComponent<FieldViewProps, InkDocume export function SetActiveInkWidth(width: string): void { !isNaN(parseInt(width)) && ActiveInkPen() && (ActiveInkPen().activeInkWidth = width); } export function SetActiveBezierApprox(bezier: string): void { ActiveInkPen() && (ActiveInkPen().activeInkBezier = isNaN(parseInt(bezier)) ? "" : bezier); } export function SetActiveInkColor(value: string) { ActiveInkPen() && (ActiveInkPen().activeInkColor = value); } +export function SetActiveFillColor(value: string) { ActiveInkPen() && (ActiveInkPen().activeFillColor = value); } +export function SetActiveArrowStart(value: string) { ActiveInkPen() && (ActiveInkPen().activeArrowStart = value); } +export function SetActiveArrowEnd(value: string) { ActiveInkPen() && (ActiveInkPen().activeArrowEnd = value); } +export function SetActiveDash(dash: string): void { !isNaN(parseInt(dash)) && ActiveInkPen() && (ActiveInkPen().activeDash = dash); } export function ActiveInkPen(): Doc { return Cast(Doc.UserDoc().activeInkPen, Doc, null); } export function ActiveInkColor(): string { return StrCast(ActiveInkPen()?.activeInkColor, "black"); } +export function ActiveFillColor(): string { return StrCast(ActiveInkPen()?.activeFillColor, "none"); } +export function ActiveArrowStart(): string { return StrCast(ActiveInkPen()?.activeArrowStart, "none"); } +export function ActiveArrowEnd(): string { return StrCast(ActiveInkPen()?.activeArrowEnd, "none"); } +export function ActiveDash(): string { return StrCast(ActiveInkPen()?.activeDash, "0"); } export function ActiveInkWidth(): string { return StrCast(ActiveInkPen()?.activeInkWidth, "1"); } export function ActiveInkBezierApprox(): string { return StrCast(ActiveInkPen()?.activeInkBezier); } -Scripting.addGlobal(function activateBrush(pen: any, width: any, color: any) { +Scripting.addGlobal(function activateBrush(pen: any, width: any, color: any, fill: any, arrowStart: any, arrowEnd: any, dash: any) { Doc.SetSelectedTool(pen ? InkTool.Highlighter : InkTool.None); SetActiveInkWidth(width); SetActiveInkColor(color); + SetActiveFillColor(fill); + SetActiveArrowStart(arrowStart); + SetActiveArrowEnd(arrowEnd); + SetActiveDash(dash); }); Scripting.addGlobal(function activateEraser(pen: any) { return Doc.SetSelectedTool(pen ? InkTool.Eraser : InkTool.None); }); Scripting.addGlobal(function activateStamp(pen: any) { return Doc.SetSelectedTool(pen ? InkTool.Stamp : InkTool.None); }); Scripting.addGlobal(function deactivateInk() { return Doc.SetSelectedTool(InkTool.None); }); Scripting.addGlobal(function setInkWidth(width: any) { return SetActiveInkWidth(width); }); -Scripting.addGlobal(function setInkColor(color: any) { return SetActiveInkColor(color); });
\ No newline at end of file +Scripting.addGlobal(function setInkColor(color: any) { return SetActiveInkColor(color); }); +Scripting.addGlobal(function setFillColor(fill: any) { return SetActiveFillColor(fill); }); +Scripting.addGlobal(function setActiveArrowStart(arrowStart: any) { return SetActiveArrowStart(arrowStart); }); +Scripting.addGlobal(function setActiveArrowEnd(arrowEnd: any) { return SetActiveArrowStart(arrowEnd); }); +Scripting.addGlobal(function setActiveDash(dash: any) { return SetActiveDash(dash); }); diff --git a/src/client/views/Main.tsx b/src/client/views/Main.tsx index 6878658a8..77e37834d 100644 --- a/src/client/views/Main.tsx +++ b/src/client/views/Main.tsx @@ -6,12 +6,14 @@ import * as React from 'react'; import { DocServer } from "../DocServer"; import { AssignAllExtensions } from "../../extensions/General/Extensions"; import { Networking } from "../Network"; +import { CollectionView } from "./collections/CollectionView"; AssignAllExtensions(); export let resolvedPorts: { server: number, socket: number }; (async () => { + window.location.search.includes("safe") && CollectionView.SetSafeMode(true); const info = await CurrentUserUtils.loadCurrentUser(); resolvedPorts = JSON.parse(await Networking.FetchFromServer("/resolvedPorts")); DocServer.init(window.location.protocol, window.location.hostname, resolvedPorts.socket, info.email); diff --git a/src/client/views/MainView.scss b/src/client/views/MainView.scss index e84969565..5b142ffda 100644 --- a/src/client/views/MainView.scss +++ b/src/client/views/MainView.scss @@ -28,10 +28,11 @@ left: 0; width: 100%; height: 100%; - pointer-events:none; + pointer-events: none; } -.mainView-container, .mainView-container-dark { +.mainView-container, +.mainView-container-dark { width: 100%; height: 100%; position: absolute; @@ -40,40 +41,50 @@ left: 0; z-index: 1; touch-action: none; + .searchBox-container { background: lightgray; } } .mainView-container { - color:dimgray; + color: dimgray; + .lm_title { background: #cacaca; - color:black; + color: black; } } .mainView-container-dark { color: lightgray; + .lm_goldenlayout { background: dimgray; } + .lm_title { background: black; - color:unset; + color: unset; } + .marquee { border-color: white; } + #search-input { background: lightgray; } - .searchBox-container { - background: rgb(45,45,45); + + .searchBox-container { + background: rgb(45, 45, 45); } - .contextMenu-cont, .contextMenu-item { + + .contextMenu-cont, + .contextMenu-item { background: dimGray; } + .contextMenu-item:hover { background: gray; } @@ -108,20 +119,27 @@ overflow: hidden; } +.buttonContainer { -.mainView-settings { position: absolute; - left: 0; bottom: 0; - border-radius: 25%; - margin-left: -5px; - background: darkblue; -} -.mainView-settings:hover { - transform: none !important; + .mainView-settings { + // position: absolute; + // left: 0; + // bottom: 0; + border-radius: 25%; + margin-left: -5px; + background: darkblue; + } + + .mainView-settings:hover { + transform: none !important; + } } + + .mainView-logout { position: absolute; right: 0; diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 4e2c067ac..15f818d1f 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -4,8 +4,8 @@ import { faTerminal, faToggleOn, faFile as fileSolid, faExternalLinkAlt, faLocationArrow, faSearch, faFileDownload, faStop, faCalculator, faWindowMaximize, faAddressCard, faQuestionCircle, faArrowLeft, faArrowRight, faArrowDown, faArrowUp, faBolt, faBullseye, faCaretUp, faCat, faCheck, faChevronRight, faClipboard, faClone, faCloudUploadAlt, faCommentAlt, faCompressArrowsAlt, faCut, faEllipsisV, faEraser, faExclamation, faFileAlt, faFileAudio, faFilePdf, faFilm, faFilter, faFont, faGlobeAsia, faHighlighter, - faLongArrowAltRight, faMicrophone, faMousePointer, faMusic, faObjectGroup, faPause, faPen, faPenNib, faPhone, faPlay, faPortrait, faRedoAlt, faStamp, faStickyNote, - faThumbtack, faTree, faTv, faUndoAlt, faVideo, faAsterisk, faBrain, faImage, faPaintBrush, faTimes, faEye, faQuoteLeft, faSortAmountDown + faLongArrowAltRight, faMicrophone, faMousePointer, faMusic, faObjectGroup, faPause, faPen, faPenNib, faPhone, faPlay, faPortrait, faRedoAlt, faStamp, faStickyNote, faTimesCircle, + faThumbtack, faTree, faTv, faUndoAlt, faVideo, faAsterisk, faBrain, faImage, faPaintBrush, faTimes, faEye, faArrowsAlt, faQuoteLeft, faSortAmountDown, faAlignLeft, faAlignCenter, faAlignRight } from '@fortawesome/free-solid-svg-icons'; import { ANTIMODEMENU_HEIGHT } from './globalCssVariables.scss'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; @@ -30,6 +30,7 @@ import { HistoryUtil } from '../util/History'; import RichTextMenu from './nodes/formattedText/RichTextMenu'; import { Scripting } from '../util/Scripting'; import SettingsManager from '../util/SettingsManager'; +import GroupManager from '../util/GroupManager'; import SharingManager from '../util/SharingManager'; import { Transform } from '../util/Transform'; import { CollectionDockingView } from './collections/CollectionDockingView'; @@ -58,6 +59,8 @@ import { DocumentManager } from '../util/DocumentManager'; import { DocumentLinksButton } from './nodes/DocumentLinksButton'; import { LinkMenu } from './linking/LinkMenu'; import { LinkDocPreview } from './nodes/LinkDocPreview'; +import { Fade } from '@material-ui/core'; +import { LinkCreatedBox } from './nodes/LinkCreatedBox'; @observer export class MainView extends React.Component { @@ -82,6 +85,8 @@ export class MainView extends React.Component { public isPointerDown = false; componentDidMount() { + DocServer.setPlaygroundFields(["dataTransition", "_viewTransition", "_panX", "_panY", "_viewScale", "_viewType"]); // can play with these fields on someone else's + const tag = document.createElement('script'); const proto = DocServer.GetRefField("rtfProto").then(proto => { @@ -95,7 +100,7 @@ export class MainView extends React.Component { window.removeEventListener("keydown", KeyManager.Instance.handle); window.addEventListener("keydown", KeyManager.Instance.handle); window.addEventListener("paste", KeyManager.Instance.paste as any); - document.addEventListener("dash", (e: any) => { // event used by chrome plugin to tell Dash which document to focus on + document.addEventListener("dash", (e: any) => { // event used by chrome plugin to tell Dash which document to focus on const id = FormattedTextBox.GetDocFromUrl(e.detail); DocServer.GetRefField(id).then(doc => { if (doc instanceof Doc) { @@ -134,11 +139,11 @@ export class MainView extends React.Component { } library.add(faTasks, faEdit, faTrashAlt, faPalette, faAngleRight, faBell, faTrash, faCamera, faExpand, faCaretDown, faCaretLeft, faCaretRight, faCaretSquareDown, faCaretSquareRight, faArrowsAltH, faPlus, faMinus, - faTerminal, faToggleOn, faExternalLinkAlt, faLocationArrow, faSearch, faFileDownload, faStop, faCalculator, faWindowMaximize, faAddressCard, fileSolid, + faTerminal, faToggleOn, faExternalLinkAlt, faLocationArrow, faSearch, faFileDownload, faStop, faCalculator, faTimesCircle, faWindowMaximize, faAddressCard, fileSolid, faQuestionCircle, faArrowLeft, faArrowRight, faArrowDown, faArrowUp, faBolt, faBullseye, faCaretUp, faCat, faCheck, faChevronRight, faClipboard, faClone, faCloudUploadAlt, faCommentAlt, faCompressArrowsAlt, faCut, faEllipsisV, faEraser, faExclamation, faFileAlt, faFileAudio, faFilePdf, faFilm, faFilter, faFont, faGlobeAsia, faHighlighter, faLongArrowAltRight, faMicrophone, faMousePointer, faMusic, faObjectGroup, faPause, faPen, faPenNib, faPhone, faPlay, faPortrait, faRedoAlt, faStamp, faStickyNote, faTrashAlt, faAngleRight, faBell, - faThumbtack, faTree, faTv, faUndoAlt, faVideo, faAsterisk, faBrain, faImage, faPaintBrush, faTimes, faEye, faQuoteLeft, faSortAmountDown); + faThumbtack, faTree, faTv, faUndoAlt, faVideo, faAsterisk, faBrain, faImage, faPaintBrush, faTimes, faEye, faArrowsAlt, faQuoteLeft, faSortAmountDown, faAlignLeft, faAlignCenter, faAlignRight); this.initEventListeners(); this.initAuthenticationRouters(); } @@ -203,7 +208,6 @@ export class MainView extends React.Component { _width: this._panelWidth * .7, _height: this._panelHeight, title: "Collection " + workspaceCount, - _LODdisable: true }; const freeformDoc = CurrentUserUtils.GuestTarget || Docs.Create.FreeformDocument([], freeformOptions); const workspaceDoc = Docs.Create.StandardCollectionDockingDocument([{ doc: freeformDoc, initialWidth: 600, path: [Doc.UserDoc().myCatalog as Doc] }], { title: `Workspace ${workspaceCount}` }, id, "row"); @@ -352,15 +356,6 @@ export class MainView extends React.Component { } @action - pointerOverDragger = () => { - // if (this.flyoutWidth === 0) { - // this.flyoutWidth = 250; - // this.sidebarButtonsDoc.columnWidth = this.flyoutWidth / 3 - 30; - // this._flyoutTranslate = false; - // } - } - - @action pointerLeaveDragger = () => { if (!this._flyoutTranslate) { this.flyoutWidth = 0; @@ -372,13 +367,13 @@ export class MainView extends React.Component { onPointerMove = (e: PointerEvent) => { this.flyoutWidth = Math.max(e.clientX, 0); Math.abs(this.flyoutWidth - this._flyoutSizeOnDown) > 6 && (this._canClick = false); - this.sidebarButtonsDoc.columnWidth = this.flyoutWidth / 3 - 30; + this.sidebarButtonsDoc._columnWidth = this.flyoutWidth / 3 - 30; } @action onPointerUp = (e: PointerEvent) => { if (Math.abs(e.clientX - this._flyoutSizeOnDown) < 4 && this._canClick) { this.flyoutWidth = this.flyoutWidth < 15 ? 250 : 0; - this.flyoutWidth && (this.sidebarButtonsDoc.columnWidth = this.flyoutWidth / 3 - 30); + this.flyoutWidth && (this.sidebarButtonsDoc._columnWidth = this.flyoutWidth / 3 - 30); } document.removeEventListener("pointermove", this.onPointerMove); document.removeEventListener("pointerup", this.onPointerUp); @@ -389,7 +384,8 @@ export class MainView extends React.Component { doc.dockingConfig ? this.openWorkspace(doc) : CollectionDockingView.AddRightSplit(doc, libraryPath); } - mainContainerXf = () => new Transform(0, -this._buttonBarHeight, 1); + sidebarScreenToLocal = () => new Transform(0, RichTextMenu.Instance.Pinned ? -35 : 0, 1); + mainContainerXf = () => this.sidebarScreenToLocal().translate(0, -this._buttonBarHeight); @computed get flyout() { const sidebarContent = this.userDoc?.["tabs-panelContainer"]; @@ -408,7 +404,7 @@ export class MainView extends React.Component { pinToPres={emptyFunction} removeDocument={undefined} onClick={undefined} - ScreenToLocalTransform={Transform.Identity} + ScreenToLocalTransform={this.sidebarScreenToLocal} ContentScaling={returnOne} NativeHeight={returnZero} NativeWidth={returnZero} @@ -450,9 +446,14 @@ export class MainView extends React.Component { docFilters={returnEmptyFilter} ContainingCollectionView={undefined} ContainingCollectionDoc={undefined} /> - <button className="mainView-settings" key="settings" onClick={() => SettingsManager.Instance.open()}> - <FontAwesomeIcon icon="cog" size="lg" /> - </button> + <div className="buttonContainer" > + <button className="mainView-settings" key="settings" onClick={() => SettingsManager.Instance.open()}> + <FontAwesomeIcon icon="cog" size="lg" /> + </button> + <button className="mainView-settings" key="groups" onClick={() => GroupManager.Instance.open()}> + <FontAwesomeIcon icon="columns" size="lg" /> + </button> + </div> </div> {this.docButtons} </div>; @@ -467,7 +468,7 @@ export class MainView extends React.Component { }} > <div style={{ display: "contents", flexDirection: "row", position: "relative" }}> <div className="mainView-flyoutContainer" onPointerLeave={this.pointerLeaveDragger} style={{ width: this.flyoutWidth }}> - <div className="mainView-libraryHandle" onPointerDown={this.onPointerDown} onPointerOver={this.pointerOverDragger} + <div className="mainView-libraryHandle" onPointerDown={this.onPointerDown} style={{ backgroundColor: this.defaultBackgroundColors(sidebar) }}> <span title="library View Dragger" style={{ width: (this.flyoutWidth !== 0 && this._flyoutTranslate) ? "100%" : "3vw", @@ -494,7 +495,7 @@ export class MainView extends React.Component { public static expandFlyout = action(() => { MainView.Instance._flyoutTranslate = true; MainView.Instance.flyoutWidth = (MainView.Instance.flyoutWidth || 250); - MainView.Instance.sidebarButtonsDoc.columnWidth = MainView.Instance.flyoutWidth / 3 - 30; + MainView.Instance.sidebarButtonsDoc._columnWidth = MainView.Instance.flyoutWidth / 3 - 30; }); @computed get expandButton() { @@ -569,11 +570,36 @@ export class MainView extends React.Component { </div>; } + @computed get inkResources() { + return <svg width={0} height={0}> + <defs> + <filter id="inkSelectionHalo"> + <feColorMatrix type="matrix" + result="color" + values="1 0 0 0 0 + 0 0 0 0 0 + 0 0 0 0 0 + 0 0 0 1 0"> + </feColorMatrix> + <feGaussianBlur in="color" stdDeviation="4" result="blur"></feGaussianBlur> + <feOffset in="blur" dx="0" dy="0" result="offset"></feOffset> + <feMerge> + <feMergeNode in="bg"></feMergeNode> + <feMergeNode in="offset"></feMergeNode> + <feMergeNode in="SourceGraphic"></feMergeNode> + </feMerge> + </filter> + </defs> + </svg>; + } + render() { return (<div className={"mainView-container" + (this.darkScheme ? "-dark" : "")} ref={this._mainViewRef}> + {this.inkResources} <DictationOverlay /> <SharingManager /> <SettingsManager /> + <GroupManager /> <GoogleAuthenticationManager /> <DocumentDecorations /> <GestureOverlay> @@ -581,6 +607,7 @@ export class MainView extends React.Component { {this.mainContent} </GestureOverlay> <PreviewCursor /> + <LinkCreatedBox /> {DocumentLinksButton.EditLink ? <LinkMenu location={DocumentLinksButton.EditLinkLoc} docView={DocumentLinksButton.EditLink} addDocTab={DocumentLinksButton.EditLink.props.addDocTab} changeFlyout={emptyFunction} /> : (null)} {LinkDocPreview.LinkInfo ? <LinkDocPreview location={LinkDocPreview.LinkInfo.Location} backgroundColor={this.defaultBackgroundColors} linkDoc={LinkDocPreview.LinkInfo.linkDoc} linkSrc={LinkDocPreview.LinkInfo.linkSrc} href={LinkDocPreview.LinkInfo.href} diff --git a/src/client/views/PreviewCursor.tsx b/src/client/views/PreviewCursor.tsx index e27f6b95a..6583589f3 100644 --- a/src/client/views/PreviewCursor.tsx +++ b/src/client/views/PreviewCursor.tsx @@ -3,12 +3,18 @@ import { observer } from 'mobx-react'; import "normalize.css"; import * as React from 'react'; import "./PreviewCursor.scss"; -import { Docs } from '../documents/Documents'; +import { Docs, DocUtils } from '../documents/Documents'; import { Doc } from '../../fields/Doc'; import { Transform } from "../util/Transform"; import { DocServer } from '../DocServer'; -import { undoBatch } from '../util/UndoManager'; +import { undoBatch, UndoManager } from '../util/UndoManager'; import { NumCast } from '../../fields/Types'; +import { FormattedTextBox } from './nodes/formattedText/FormattedTextBox'; +import * as rp from 'request-promise'; +import { Utils } from '../../Utils'; +import { Networking } from '../Network'; +import { Upload } from '../../server/SharedMediaTypes'; +import { basename } from 'path'; @observer export class PreviewCursor extends React.Component<{}> { @@ -25,7 +31,7 @@ export class PreviewCursor extends React.Component<{}> { document.addEventListener("paste", this.paste); } - paste = (e: ClipboardEvent) => { + paste = async (e: ClipboardEvent) => { if (PreviewCursor.Visible && e.clipboardData) { const newPoint = PreviewCursor._getTransform().transformPoint(PreviewCursor._clickPoint[0], PreviewCursor._clickPoint[1]); runInAction(() => PreviewCursor.Visible = false); @@ -81,6 +87,7 @@ export class PreviewCursor extends React.Component<{}> { e.stopPropagation(); } else { // creates text document + FormattedTextBox.PasteOnLoad = e; undoBatch(() => PreviewCursor._addLiveTextDoc(Docs.Create.TextDocument("", { _width: 500, limitHeight: 400, @@ -102,6 +109,16 @@ export class PreviewCursor extends React.Component<{}> { x: newPoint[0], y: newPoint[1], })))(); + } else if (e.clipboardData.items.length) { + const batch = UndoManager.StartBatch("collection view drop"); + const files: File[] = []; + for (let i = 0; i < e.clipboardData.items.length; i++) { + const file = e.clipboardData.items[i].getAsFile(); + file && files.push(file); + } + const generatedDocuments = await DocUtils.uploadFilesToDocs(files, { x: newPoint[0], y: newPoint[1] }); + generatedDocuments.forEach(PreviewCursor._addDocument); + batch.end(); } } } diff --git a/src/client/views/animationtimeline/Timeline.tsx b/src/client/views/animationtimeline/Timeline.tsx index ab984f727..f54bd3aff 100644 --- a/src/client/views/animationtimeline/Timeline.tsx +++ b/src/client/views/animationtimeline/Timeline.tsx @@ -288,13 +288,13 @@ export class Timeline extends React.Component<FieldViewProps> { resetView(doc: Doc) { doc._panX = doc._customOriginX ?? 0; doc._panY = doc._customOriginY ?? 0; - doc.scale = doc._customOriginScale ?? 1; + doc._viewScale = doc._customOriginScale ?? 1; } setView(doc: Doc) { doc._customOriginX = doc._panX; doc._customOriginY = doc._panY; - doc._customOriginScale = doc.scale; + doc._customOriginScale = doc._viewScale; } /** * zooming mechanism (increment and spacing changes) diff --git a/src/client/views/collections/CollectionCarousel3DView.scss b/src/client/views/collections/CollectionCarousel3DView.scss new file mode 100644 index 000000000..5f8895c1f --- /dev/null +++ b/src/client/views/collections/CollectionCarousel3DView.scss @@ -0,0 +1,107 @@ +.collectionCarousel3DView-outer { + height: 100%; + position: relative; + background-color: white; +} + +.carousel-wrapper { + display: flex; + position: absolute; + top: 15%; + align-items: center; + transition: transform 0.3s cubic-bezier(0.455, 0.03, 0.515, 0.955); + + .collectionCarousel3DView-item, + .collectionCarousel3DView-item-active { + flex: 1; + transition: opacity 0.3s linear, transform 0.5s cubic-bezier(0.455, 0.03, 0.515, 0.955); + pointer-events: none; + } + + .collectionCarousel3DView-item-active { + pointer-events: unset; + } +} + +.dot-bar { + display: flex; + position: absolute; + justify-content: center; + bottom: 5%; + width: 100%; + + .dot, + .dot-active { + height: 10px; + width: 10px; + border-radius: 50%; + margin: 3px; + display: inline-block; + background-color: lightgrey; + cursor: pointer; + } + + .dot-active { + background-color: grey; + } +} + +.carousel3DView-back, +.carousel3DView-fwd, +.carousel3DView-back-scroll, +.carousel3DView-fwd-scroll, +.carousel3DView-back-scroll-hidden, +.carousel3DView-fwd-scroll-hidden { + position: absolute; + display: flex; + width: 30; + height: 30; + align-items: center; + border-radius: 5px; + justify-content: center; + background: rgba(255, 255, 255, 0.46); + cursor: pointer; +} + +.carousel3DView-fwd, +.carousel3DView-back { + top: 50%; +} + +.carousel3DView-fwd-scroll, +.carousel3DView-back-scroll, +.carousel3DView-fwd-scroll-hidden, +.carousel3DView-back-scroll-hidden { + top: calc(50% - 30px); +} + +.carousel3DView-fwd, +.carousel3DView-fwd-scroll, +.carousel3DView-fwd-scroll-hidden { + right: 0; +} + +.carousel3DView-back, +.carousel3DView-back-scroll, +.carousel3DView-back-scroll-hidden { + left: 0; +} + +.carousel3DView-fwd-scroll-hidden, +.carousel3DView-back-scroll-hidden { + opacity: 0; + transition: opacity 0.5s linear; + pointer-events: none; +} + +.carousel3DView-fwd-scroll, +.carousel3DView-back-scroll { + opacity: 1; +} + +.carousel3DView-back:hover, +.carousel3DView-fwd:hover, +.carousel3DView-back-scroll:hover, +.carousel3DView-fwd-scroll:hover { + background: lightgray; +}
\ No newline at end of file diff --git a/src/client/views/collections/CollectionCarousel3DView.tsx b/src/client/views/collections/CollectionCarousel3DView.tsx new file mode 100644 index 000000000..1344b70f4 --- /dev/null +++ b/src/client/views/collections/CollectionCarousel3DView.tsx @@ -0,0 +1,197 @@ +import { computed } from 'mobx'; +import { observer } from 'mobx-react'; +import * as React from 'react'; +import { documentSchema, collectionSchema } from '../../../fields/documentSchemas'; +import { makeInterface } from '../../../fields/Schema'; +import { NumCast, StrCast, ScriptCast } from '../../../fields/Types'; +import { DragManager } from '../../util/DragManager'; +import { ContentFittingDocumentView } from '../nodes/ContentFittingDocumentView'; +import "./CollectionCarousel3DView.scss"; +import { CollectionSubView } from './CollectionSubView'; +import { Doc } from '../../../fields/Doc'; +import { ContextMenu } from '../ContextMenu'; +import { ObjectField } from '../../../fields/ObjectField'; +import { returnFalse, Utils } from '../../../Utils'; +import { ScriptField } from '../../../fields/ScriptField'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { Id } from '../../../fields/FieldSymbols'; + +type Carousel3DDocument = makeInterface<[typeof documentSchema, typeof collectionSchema]>; +const Carousel3DDocument = makeInterface(documentSchema, collectionSchema); + +@observer +export class CollectionCarousel3DView extends CollectionSubView(Carousel3DDocument) { + @computed get scrollSpeed() { + return this.layoutDoc._autoScrollSpeed ? NumCast(this.layoutDoc._autoScrollSpeed) : 1000; //default scroll speed + } + + private _dropDisposer?: DragManager.DragDropDisposer; + + componentWillUnmount() { this._dropDisposer?.(); } + + protected createDashEventsTarget = (ele: HTMLDivElement) => { //used for stacking and masonry view + this._dropDisposer?.(); + if (ele) { + this._dropDisposer = DragManager.MakeDropTarget(ele, this.onInternalDrop.bind(this), this.layoutDoc); + } + } + + panelWidth = () => this.props.PanelWidth() / 3; + panelHeight = () => this.props.PanelHeight() * 0.6; + @computed get content() { + const currentIndex = NumCast(this.layoutDoc._itemIndex); + const displayDoc = (childPair: { layout: Doc, data: Doc }) => { + return <ContentFittingDocumentView {...this.props} + onDoubleClick={ScriptCast(this.layoutDoc.onChildDoubleClick)} + onClick={ScriptField.MakeScript( + "child._showCaption = 'caption'", + { child: Doc.name }, + { child: childPair.layout })} + renderDepth={this.props.renderDepth + 1} + LayoutTemplate={this.props.ChildLayoutTemplate} + LayoutTemplateString={this.props.ChildLayoutString} + Document={childPair.layout} + DataDoc={childPair.data} + PanelWidth={this.panelWidth} + PanelHeight={this.panelHeight} + ScreenToLocalTransform={this.props.ScreenToLocalTransform} + bringToFront={returnFalse} + parentActive={this.props.active} + />; + }; + + return (this.childLayoutPairs.map((childPair, index) => { + return ( + <div key={childPair.layout[Id]} + className={`collectionCarousel3DView-item${index === currentIndex ? "-active" : ""} ${index}`} + style={index === currentIndex ? + { opacity: '1', transform: 'scale(1.3)' } : + { opacity: '0.5', transform: 'scale(0.6)', userSelect: 'none' }}> + {displayDoc(childPair)} + </div>); + })); + } + + changeSlide = (direction: number) => { + this.layoutDoc._itemIndex = (NumCast(this.layoutDoc._itemIndex) + direction + this.childLayoutPairs.length) % this.childLayoutPairs.length; + } + + onArrowClick = (e: React.MouseEvent, direction: number) => { + e.stopPropagation(); + this.changeSlide(direction); + !this.layoutDoc.autoScrollOn && (this.layoutDoc.showScrollButton = (direction === 1) ? "fwd" : "back"); // while autoscroll is on, keep the other autoscroll button hidden + !this.layoutDoc.autoScrollOn && this.fadeScrollButton(); // keep pause button visible while autoscroll is on + } + + interval?: number; + startAutoScroll = (direction: number) => { + this.interval = window.setInterval(() => { + console.log(this.interval, this.scrollSpeed); + this.changeSlide(direction); + }, this.scrollSpeed); + } + + stopAutoScroll = () => { + window.clearInterval(this.interval); + this.interval = undefined; + this.fadeScrollButton(); + } + + toggleAutoScroll = (direction: number) => { + this.layoutDoc.autoScrollOn = this.layoutDoc.autoScrollOn ? false : true; + this.layoutDoc.autoScrollOn ? this.startAutoScroll(direction) : this.stopAutoScroll(); + } + + fadeScrollButton = () => { + window.setTimeout(() => { + !this.layoutDoc.autoScrollOn && (this.layoutDoc.showScrollButton = "none"); //fade away after 1.5s if it's not clicked. + }, 1500); + } + + onContextMenu = (e: React.MouseEvent): void => { + // need to test if propagation has stopped because GoldenLayout forces a parallel react hierarchy to be created for its top-level layout + if (!e.isPropagationStopped()) { + ContextMenu.Instance.addItem({ + description: "Make Hero Image", event: () => { + const index = NumCast(this.layoutDoc._itemIndex); + (this.dataDoc || Doc.GetProto(this.props.Document)).hero = ObjectField.MakeCopy(this.childLayoutPairs[index].layout.data as ObjectField); + }, icon: "plus" + }); + } + } + _downX = 0; + _downY = 0; + onPointerDown = (e: React.PointerEvent) => { + this._downX = e.clientX; + this._downY = e.clientY; + console.log("CAROUSEL down"); + document.addEventListener("pointerup", this.onpointerup); + } + private _lastTap: number = 0; + private _doubleTap = false; + onpointerup = (e: PointerEvent) => { + console.log("CAROUSEL up"); + this._doubleTap = (Date.now() - this._lastTap < 300 && e.button === 0 && Math.abs(e.clientX - this._downX) < 2 && Math.abs(e.clientY - this._downY) < 2); + this._lastTap = Date.now(); + } + + onClick = (e: React.MouseEvent) => { + if (this._doubleTap) { + e.stopPropagation(); + this.props.Document.isLightboxOpen = true; + } + } + + @computed get buttons() { + if (!this.props.active()) return null; + return <div className="arrow-buttons" > + <div key="back" className="carousel3DView-back" style={{ background: `${StrCast(this.props.Document.backgroundColor)}` }} + onClick={(e) => this.onArrowClick(e, -1)} + > + <FontAwesomeIcon icon={"angle-left"} size={"2x"} /> + </div> + <div key="fwd" className="carousel3DView-fwd" style={{ background: `${StrCast(this.props.Document.backgroundColor)}` }} + onClick={(e) => this.onArrowClick(e, 1)} + > + <FontAwesomeIcon icon={"angle-right"} size={"2x"} /> + </div> + {this.autoScrollButton} + </div>; + } + + @computed get autoScrollButton() { + const whichButton = this.layoutDoc.showScrollButton; + return <> + <div className={`carousel3DView-back-scroll${whichButton === "back" ? "" : "-hidden"}`} style={{ background: `${StrCast(this.props.Document.backgroundColor)}` }} + onClick={() => this.toggleAutoScroll(-1)}> + {this.layoutDoc.autoScrollOn ? <FontAwesomeIcon icon={"pause"} size={"1x"} /> : <FontAwesomeIcon icon={"angle-double-left"} size={"1x"} />} + </div> + <div className={`carousel3DView-fwd-scroll${whichButton === "fwd" ? "" : "-hidden"}`} style={{ background: `${StrCast(this.props.Document.backgroundColor)}` }} + onClick={() => this.toggleAutoScroll(1)}> + {this.layoutDoc.autoScrollOn ? <FontAwesomeIcon icon={"pause"} size={"1x"} /> : <FontAwesomeIcon icon={"angle-double-right"} size={"1x"} />} + </div> + </>; + } + + @computed get dots() { + return (this.childLayoutPairs.map((_child, index) => { + return <div key={Utils.GenerateGuid()} className={`dot${index === NumCast(this.layoutDoc._itemIndex) ? "-active" : ""}`} + onClick={() => this.layoutDoc._itemIndex = index} />; + })); + } + + render() { + const index = NumCast(this.layoutDoc._itemIndex); + const translateX = (1 - index) / this.childLayoutPairs.length * 100; + + return <div className="collectionCarousel3DView-outer" onClick={this.onClick} onPointerDown={this.onPointerDown} ref={this.createDashEventsTarget} onContextMenu={this.onContextMenu}> + <div className="carousel-wrapper" style={{ transform: `translateX(calc(${translateX}%` }}> + {this.content} + </div> + {this.props.Document._chromeStatus !== "replaced" ? this.buttons : (null)} + <div className="dot-bar"> + {this.dots} + </div> + </div>; + } +}
\ No newline at end of file diff --git a/src/client/views/collections/CollectionCarouselView.tsx b/src/client/views/collections/CollectionCarouselView.tsx index f65a89422..bd0e4fc9a 100644 --- a/src/client/views/collections/CollectionCarouselView.tsx +++ b/src/client/views/collections/CollectionCarouselView.tsx @@ -87,7 +87,7 @@ export class CollectionCarouselView extends CollectionSubView(CarouselDocument) onContextMenu = (e: React.MouseEvent): void => { // need to test if propagation has stopped because GoldenLayout forces a parallel react hierarchy to be created for its top-level layout if (!e.isPropagationStopped()) { - ContextMenu.Instance.addItem({ + ContextMenu.Instance?.addItem({ description: "Make Hero Image", event: () => { const index = NumCast(this.layoutDoc._itemIndex); (this.dataDoc || Doc.GetProto(this.props.Document)).hero = ObjectField.MakeCopy(this.childLayoutPairs[index].layout.data as ObjectField); diff --git a/src/client/views/collections/CollectionLinearView.scss b/src/client/views/collections/CollectionLinearView.scss index 123a27deb..5ada79a28 100644 --- a/src/client/views/collections/CollectionLinearView.scss +++ b/src/client/views/collections/CollectionLinearView.scss @@ -1,12 +1,51 @@ @import "../globalCssVariables"; @import "../_nodeModuleOverrides"; -.collectionLinearView-outer{ +.collectionLinearView-outer { overflow: hidden; - height:100%; + height: 100%; + .collectionLinearView { - display:flex; + display: flex; height: 100%; + + >span { + background: $dark-color; + color: $light-color; + border-radius: 18px; + margin-right: 6px; + cursor: pointer; + } + + .bottomPopup-background { + padding-right: 14px; + height: 35; + transform: translate3d(6px, 5px, 0px); + padding-top: 6.5px; + padding-bottom: 7px; + padding-left: 5px; + } + + .bottomPopup-text { + display: inline; + white-space: nowrap; + padding-left: 8px; + padding-right: 4px; + vertical-align: middle; + font-size: 12.5px; + } + + .bottomPopup-exit { + display: inline; + white-space: nowrap; + padding-left: 8px; + padding-right: 8px; + vertical-align: middle; + background-color: lightgrey; + border-radius: 5.5px; + color: black; + } + >label { margin-top: "auto"; margin-bottom: "auto"; @@ -17,15 +56,15 @@ font-size: 12.5px; width: 18px; height: 18px; - margin-top:auto; - margin-bottom:auto; + margin-top: auto; + margin-bottom: auto; margin-right: 3px; cursor: pointer; transition: transform 0.2s; } label p { - padding-left:5px; + padding-left: 5px; } label:hover { @@ -36,6 +75,7 @@ >input { display: none; } + >input:not(:checked)~.collectionLinearView-content { display: none; } @@ -52,12 +92,14 @@ position: relative; margin-top: auto; - .collectionLinearView-docBtn, .collectionLinearView-docBtn-scalable { - position:relative; - margin:auto; + .collectionLinearView-docBtn, + .collectionLinearView-docBtn-scalable { + position: relative; + margin: auto; margin-left: 3px; transform-origin: center 80%; } + .collectionLinearView-docBtn-scalable:hover { transform: scale(1.15); } @@ -68,10 +110,10 @@ border-radius: 18px; font-size: 15px; } - + .collectionLinearView-round-button:hover { transform: scale(1.15); } } } -} +}
\ No newline at end of file diff --git a/src/client/views/collections/CollectionLinearView.tsx b/src/client/views/collections/CollectionLinearView.tsx index f38eeaf41..7cbe5c19d 100644 --- a/src/client/views/collections/CollectionLinearView.tsx +++ b/src/client/views/collections/CollectionLinearView.tsx @@ -13,6 +13,8 @@ import { CollectionSubView } from './CollectionSubView'; import { DocumentView } from '../nodes/DocumentView'; import { documentSchema } from '../../../fields/documentSchemas'; import { Id } from '../../../fields/FieldSymbols'; +import { DocumentLinksButton } from '../nodes/DocumentLinksButton'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; type LinearDocument = makeInterface<[typeof documentSchema,]>; @@ -75,6 +77,18 @@ export class CollectionLinearView extends CollectionSubView(LinearDocument) { return new Transform(-translateX, -translateY, 1); } + @action + exitLongLinks = () => { + if (DocumentLinksButton.StartLink) { + if (DocumentLinksButton.StartLink.Document) { + action((e: React.PointerEvent<HTMLDivElement>) => { + Doc.UnBrushDoc(DocumentLinksButton.StartLink?.Document as Doc); + }); + } + } + DocumentLinksButton.StartLink = undefined; + } + render() { const guid = Utils.GenerateGuid(); const flexDir: any = StrCast(this.Document.flexDirection); @@ -82,7 +96,12 @@ export class CollectionLinearView extends CollectionSubView(LinearDocument) { const color = StrCast(this.props.Document.color, "white"); return <div className="collectionLinearView-outer"> <div className="collectionLinearView" ref={this.createDashEventsTarget} > - <label htmlFor={`${guid}`} title="Close Menu" style={{ background: backgroundColor === color ? "black" : backgroundColor }} + <label htmlFor={`${guid}`} title="Close Menu" style={{ + background: backgroundColor === color ? "black" : backgroundColor, + // width: "18px", height: "18px", fontSize: "12.5px", + // transition: this.props.Document.linearViewIsExpanded ? "transform 0.2s" : "transform 0.5s", + // transform: this.props.Document.linearViewIsExpanded ? "" : "rotate(45deg)" + }} onPointerDown={e => e.stopPropagation()} > <p>+</p> </label> @@ -130,6 +149,19 @@ export class CollectionLinearView extends CollectionSubView(LinearDocument) { </div>; })} </div> + {DocumentLinksButton.StartLink ? <span className="bottomPopup-background" style={{ + background: backgroundColor === color ? "black" : backgroundColor + }} + onPointerDown={e => e.stopPropagation()} > + <span className="bottomPopup-text" > + Creating link from: {DocumentLinksButton.StartLink.title} </span> + <span className="bottomPopup-exit" onClick={this.exitLongLinks} + >Exit</span> + + {/* <FontAwesomeIcon icon="times-circle" size="lg" style={{ color: "red" }} + onClick={this.exitLongLinks} /> */} + + </span> : null} </div> </div>; } diff --git a/src/client/views/collections/CollectionMasonryViewFieldRow.tsx b/src/client/views/collections/CollectionMasonryViewFieldRow.tsx index e0b53e762..627b22417 100644 --- a/src/client/views/collections/CollectionMasonryViewFieldRow.tsx +++ b/src/client/views/collections/CollectionMasonryViewFieldRow.tsx @@ -111,8 +111,8 @@ export class CollectionMasonryViewFieldRow extends React.Component<CMVFieldRowPr const key = StrCast(this.props.parent.props.Document._pivotField); const castedValue = this.getValue(value); if (castedValue) { - if (this.props.parent.sectionHeaders) { - if (this.props.parent.sectionHeaders.map(i => i.heading).indexOf(castedValue.toString()) > -1) { + if (this.props.parent.columnHeaders) { + if (this.props.parent.columnHeaders.map(i => i.heading).indexOf(castedValue.toString()) > -1) { return false; } } @@ -151,9 +151,9 @@ export class CollectionMasonryViewFieldRow extends React.Component<CMVFieldRowPr this._createAliasSelected = false; const key = StrCast(this.props.parent.props.Document._pivotField); this.props.docList.forEach(d => d[key] = undefined); - if (this.props.parent.sectionHeaders && this.props.headingObject) { - const index = this.props.parent.sectionHeaders.indexOf(this.props.headingObject); - this.props.parent.sectionHeaders.splice(index, 1); + if (this.props.parent.columnHeaders && this.props.headingObject) { + const index = this.props.parent.columnHeaders.indexOf(this.props.headingObject); + this.props.parent.columnHeaders.splice(index, 1); } })); diff --git a/src/client/views/collections/CollectionSchemaCells.tsx b/src/client/views/collections/CollectionSchemaCells.tsx index 2b8110e27..d76b6d204 100644 --- a/src/client/views/collections/CollectionSchemaCells.tsx +++ b/src/client/views/collections/CollectionSchemaCells.tsx @@ -1,22 +1,22 @@ import React = require("react"); -import { action, observable, trace } from "mobx"; +import { action, observable, trace, computed } from "mobx"; import { observer } from "mobx-react"; import { CellInfo } from "react-table"; import "react-table/react-table.css"; -import { emptyFunction, returnFalse, returnZero, returnOne, returnEmptyFilter } from "../../../Utils"; +import { emptyFunction, returnFalse, returnZero, returnOne, returnEmptyFilter, Utils, emptyPath } from "../../../Utils"; import { Doc, DocListCast, Field, Opt } from "../../../fields/Doc"; import { Id } from "../../../fields/FieldSymbols"; import { KeyCodes } from "../../util/KeyCodes"; import { SetupDrag, DragManager } from "../../util/DragManager"; import { CompileScript } from "../../util/Scripting"; import { Transform } from "../../util/Transform"; -import { MAX_ROW_HEIGHT } from '../globalCssVariables.scss'; +import { MAX_ROW_HEIGHT, COLLECTION_BORDER_WIDTH } from '../globalCssVariables.scss'; import '../DocumentDecorations.scss'; import { EditableView } from "../EditableView"; import { FieldView, FieldViewProps } from "../nodes/FieldView"; import "./CollectionSchemaView.scss"; -import { CollectionView } from "./CollectionView"; -import { NumCast, StrCast, BoolCast, FieldValue, Cast } from "../../../fields/Types"; +import { CollectionView, Flyout } from "./CollectionView"; +import { NumCast, StrCast, BoolCast, FieldValue, Cast, DateCast } from "../../../fields/Types"; import { Docs } from "../../documents/Documents"; import { library } from '@fortawesome/fontawesome-svg-core'; import { faExpand } from '@fortawesome/free-solid-svg-icons'; @@ -24,6 +24,15 @@ import { SchemaHeaderField } from "../../../fields/SchemaHeaderField"; import { undoBatch } from "../../util/UndoManager"; import { SnappingManager } from "../../util/SnappingManager"; import { ComputedField } from "../../../fields/ScriptField"; +import { ImageField } from "../../../fields/URLField"; +import { List } from "../../../fields/List"; +import { OverlayView } from "../OverlayView"; +import { DocumentIconContainer } from "../nodes/DocumentIcon"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import DatePicker from "react-datepicker"; +import "react-datepicker/dist/react-datepicker.css"; +import { DateField } from "../../../fields/DateField"; +const path = require('path'); library.add(faExpand); @@ -47,6 +56,7 @@ export interface CellProps { setPreviewDoc: (doc: Doc) => void; setComputed: (script: string, doc: Doc, field: string, row: number, col: number) => boolean; getField: (row: number, col?: number) => void; + showDoc: (doc: Doc | undefined, dataDoc?: any, screenX?: number, screenY?: number) => void; } @observer @@ -54,7 +64,7 @@ export class CollectionSchemaCell extends React.Component<CellProps> { @observable protected _isEditing: boolean = false; protected _focusRef = React.createRef<HTMLDivElement>(); protected _document = this.props.rowProps.original; - private _dropDisposer?: DragManager.DragDropDisposer; + protected _dropDisposer?: DragManager.DragDropDisposer; componentDidMount() { document.addEventListener("keydown", this.onKeyDown); @@ -84,6 +94,7 @@ export class CollectionSchemaCell extends React.Component<CellProps> { @action onPointerDown = async (e: React.PointerEvent): Promise<void> => { + this.props.changeFocusedCellByIndex(this.props.row, this.props.col); this.props.setPreviewDoc(this.props.rowProps.original); @@ -129,7 +140,7 @@ export class CollectionSchemaCell extends React.Component<CellProps> { } } - private dropRef = (ele: HTMLElement | null) => { + protected dropRef = (ele: HTMLElement | null) => { this._dropDisposer && this._dropDisposer(); if (ele) { this._dropDisposer = DragManager.MakeDropTarget(ele, this.drop.bind(this)); @@ -206,6 +217,18 @@ export class CollectionSchemaCell extends React.Component<CellProps> { const doc = FieldValue(Cast(field, Doc)); contents = typeof field === "object" ? doc ? StrCast(doc.title) === "" ? "--" : StrCast(doc.title) : `--${typeof field}--` : `--${typeof field}--`; } + if (type === "image") { + const image = FieldValue(Cast(field, ImageField)); + const doc = FieldValue(Cast(field, Doc)); + contents = typeof field === "object" ? doc ? StrCast(doc.title) === "" ? "--" : StrCast(doc.title) : `--${typeof field}--` : `--${typeof field}--`; + } + if (type === "list") { + contents = typeof field === "object" ? doc ? StrCast(field) === "" ? "--" : StrCast(field) : `--${typeof field}--` : `--${typeof field}--`; + } + if (type === "date") { + contents = typeof field === "object" ? doc ? StrCast(field) === "" ? "--" : StrCast(field) : `--${typeof field}--` : `--${typeof field}--`; + } + let className = "collectionSchemaView-cellWrapper"; if (this._isEditing) className += " editing"; @@ -220,40 +243,60 @@ export class CollectionSchemaCell extends React.Component<CellProps> { // ); trace(); + + return ( <div className="collectionSchemaView-cellContainer" style={{ cursor: fieldIsDoc ? "grab" : "auto" }} ref={dragRef} onPointerDown={this.onPointerDown} onPointerEnter={onPointerEnter} onPointerLeave={onPointerLeave}> <div className={className} ref={this._focusRef} onPointerDown={onItemDown} tabIndex={-1}> <div className="collectionSchemaView-cellContents" ref={type === undefined || type === "document" ? this.dropRef : null} key={props.Document[Id]}> + + <EditableView editing={this._isEditing} isEditingCallback={this.isEditingCallback} display={"inline"} - contents={contents} + contents={contents ? contents : type === "number" ? "0" : "undefined"} + //contents={StrCast(contents)} height={"auto"} maxHeight={Number(MAX_ROW_HEIGHT)} + placeholder={"enter value"} GetValue={() => { - 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; + if (type === "number" && (contents === 0 || contents === "0")) { + return "0"; + } else { + const cfield = ComputedField.WithoutComputed(() => FieldValue(props.Document[props.fieldKey])); + console.log(cfield); + if (type === "number") { + return StrCast(cfield); + } + const cscript = cfield instanceof ComputedField ? cfield.script.originalScript : undefined; + const cfinalScript = cscript?.split("return")[cscript.split("return").length - 1]; + const val = cscript !== undefined ? (cfinalScript?.endsWith(";") ? `:=${cfinalScript?.substring(0, cfinalScript.length - 2)}` : cfinalScript) : + Field.IsField(cfield) ? Field.toScriptString(cfield) : ""; + return val; + } + }} SetValue={action((value: string) => { let retVal = false; + if (value.startsWith(":=")) { 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); + console.log("compiled"); } + } 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 retVal; + + //return true; })} 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" } }); @@ -265,6 +308,8 @@ export class CollectionSchemaCell extends React.Component<CellProps> { } }} /> + + </div > {/* {fieldIsDoc ? docExpander : null} */} </div> @@ -299,12 +344,473 @@ export class CollectionSchemaStringCell extends CollectionSchemaCell { } @observer +export class CollectionSchemaDateCell extends CollectionSchemaCell { + @observable private _date: Date = this.props.rowProps.original[this.props.rowProps.column.id as string] instanceof DateField ? DateCast(this.props.rowProps.original[this.props.rowProps.column.id as string]).date : + this.props.rowProps.original[this.props.rowProps.column.id as string] instanceof Date ? this.props.rowProps.original[this.props.rowProps.column.id as string] : new Date(); + + @action + handleChange = (date: any) => { + console.log(date); + this._date = date; + // const script = CompileScript(date.toString(), { requiredType: "Date", addReturn: true, params: { this: Doc.name } }); + // if (script.compiled) { + // console.log("scripting"); + // this.applyToDoc(this._document, this.props.row, this.props.col, script.run); + // } else { + console.log(DateCast(date)); + // ^ DateCast is always undefined for some reason, but that is what the field should be set to + this._document[this.props.rowProps.column.id as string] = date as Date; + console.log(this._document[this.props.rowProps.column.id as string]); + //} + } + + render() { + return <DatePicker + selected={this._date} + onSelect={date => this.handleChange(date)} + onChange={date => this.handleChange(date)} + />; + } +} + +@observer export class CollectionSchemaDocCell extends CollectionSchemaCell { + + _overlayDisposer?: () => void; + + private prop: FieldViewProps = { + Document: this.props.rowProps.original, + DataDoc: this.props.rowProps.original, + LibraryPath: [], + dropAction: "alias", + bringToFront: emptyFunction, + rootSelected: returnFalse, + fieldKey: this.props.rowProps.column.id as string, + ContainingCollectionView: this.props.CollectionView, + ContainingCollectionDoc: this.props.CollectionView && this.props.CollectionView.props.Document, + isSelected: returnFalse, + select: emptyFunction, + renderDepth: this.props.renderDepth + 1, + ScreenToLocalTransform: Transform.Identity, + focus: emptyFunction, + active: returnFalse, + whenActiveChanged: emptyFunction, + PanelHeight: returnZero, + PanelWidth: returnZero, + NativeHeight: returnZero, + NativeWidth: returnZero, + addDocTab: this.props.addDocTab, + pinToPres: this.props.pinToPres, + ContentScaling: returnOne, + docFilters: returnEmptyFilter + }; + @observable private _field = this.prop.Document[this.prop.fieldKey]; + @observable private _doc = FieldValue(Cast(this._field, Doc)); + @observable private _docTitle = this._doc?.title; + @observable private _preview = false; + @computed get previewWidth() { return () => NumCast(this.props.Document.schemaPreviewWidth); } + @computed get borderWidth() { return Number(COLLECTION_BORDER_WIDTH); } + @computed get tableWidth() { return this.prop.PanelWidth() - 2 * this.borderWidth - 4 - this.previewWidth(); } + + @action + onSetValue = (value: string) => { + this._docTitle = value; + //this.prop.Document[this.prop.fieldKey] = this._text; + + const script = CompileScript(value, { + addReturn: true, + typecheck: false, + transformer: DocumentIconContainer.getTransformer() + }); + + const results = script.compiled && script.run(); + if (results && results.success) { + + console.log(results.result); + this._doc = results.result; + this._document[this.prop.fieldKey] = results.result; + this._docTitle = this._doc?.title; + + return true; + } + return false; + } + + onFocus = () => { + this._overlayDisposer?.(); + this._overlayDisposer = OverlayView.Instance.addElement(<DocumentIconContainer />, { x: 0, y: 0 }); + } + + @action + onOpenClick = () => { + this._preview = false; + if (this._doc) { + this.props.addDocTab(this._doc, "onRight"); + return true; + } + return false; + } + + @action + showPreview = (bool: boolean, e: any) => { + if (this._isEditing) { + this._preview = false; + } else { + if (bool) { + console.log("show doc"); + this.props.showDoc(this._doc, this.prop.DataDoc, e.clientX, e.clientY); + } else { + console.log("no doc"); + this.props.showDoc(undefined); + } + } + } + + @action + isEditingCalling = (isEditing: boolean): void => { + this.showPreview(false, ""); + document.removeEventListener("keydown", this.onKeyDown); + isEditing && document.addEventListener("keydown", this.onKeyDown); + this._isEditing = isEditing; + this.props.setIsEditing(isEditing); + this.props.changeFocusedCellByIndex(this.props.row, this.props.col); + } + + onDown = (e: any) => { + this.props.changeFocusedCellByIndex(this.props.row, this.props.col); + this.props.setPreviewDoc(this.props.rowProps.original); + + let url: string; + if (url = StrCast(this.props.rowProps.row.href)) { + try { + new URL(url); + const temp = window.open(url)!; + temp.blur(); + window.focus(); + } catch { } + } + + const field = this.props.rowProps.original[this.props.rowProps.column.id!]; + const doc = FieldValue(Cast(field, Doc)); + if (typeof field === "object" && doc) this.props.setPreviewDoc(doc); + + this.showPreview(true, e); + + } + render() { - return this.renderCellWithType("document"); + if (typeof this._field === "object" && this._doc && this._docTitle) { + return ( + <div className="collectionSchemaView-cellWrapper" ref={this._focusRef} tabIndex={-1} + onPointerDown={(e) => { this.onDown(e); }} + onPointerEnter={(e) => { this.showPreview(true, e); }} + onPointerLeave={(e) => { this.showPreview(false, e); }} + > + + <div className="collectionSchemaView-cellContents-document" + style={{ padding: "5.9px" }} + ref={this.dropRef} + onFocus={this.onFocus} + onBlur={() => this._overlayDisposer?.()} + > + + <EditableView + editing={this._isEditing} + isEditingCallback={this.isEditingCalling} + display={"inline"} + contents={this._docTitle} + height={"auto"} + maxHeight={Number(MAX_ROW_HEIGHT)} + GetValue={() => { + return StrCast(this._docTitle); + }} + SetValue={action((value: string) => { + this.onSetValue(value); + this.showPreview(false, ""); + return true; + })} + /> + </div > + <div onClick={this.onOpenClick} className="collectionSchemaView-cellContents-docButton"> + <FontAwesomeIcon icon="external-link-alt" size="lg" ></FontAwesomeIcon> </div> + </div> + ); + } else { + return this.renderCellWithType("document"); + } + } +} + +@observer +export class CollectionSchemaImageCell extends CollectionSchemaCell { + // render() { + // return this.renderCellWithType("image"); + // } + + choosePath(url: URL, dataDoc: any) { + const lower = url.href.toLowerCase(); + if (url.protocol === "data") { + return url.href; + } else if (url.href.indexOf(window.location.origin) === -1) { + return Utils.CorsProxy(url.href); + } else if (!/\.(png|jpg|jpeg|gif|webp)$/.test(lower)) { + return url.href;//Why is this here + } + const ext = path.extname(url.href); + const _curSuffix = "_o"; + return url.href.replace(ext, _curSuffix + ext); + } + + render() { + const props: FieldViewProps = { + Document: this.props.rowProps.original, + DataDoc: this.props.rowProps.original, + LibraryPath: [], + dropAction: "alias", + bringToFront: emptyFunction, + rootSelected: returnFalse, + fieldKey: this.props.rowProps.column.id as string, + ContainingCollectionView: this.props.CollectionView, + ContainingCollectionDoc: this.props.CollectionView && this.props.CollectionView.props.Document, + isSelected: returnFalse, + select: emptyFunction, + renderDepth: this.props.renderDepth + 1, + ScreenToLocalTransform: Transform.Identity, + focus: emptyFunction, + active: returnFalse, + whenActiveChanged: emptyFunction, + PanelHeight: returnZero, + PanelWidth: returnZero, + NativeHeight: returnZero, + NativeWidth: returnZero, + addDocTab: this.props.addDocTab, + pinToPres: this.props.pinToPres, + ContentScaling: returnOne, + docFilters: returnEmptyFilter + }; + + let image = true; + let url = []; + if (props.DataDoc) { + const field = Cast(props.DataDoc[props.fieldKey], ImageField, null); // retrieve the primary image URL that is being rendered from the data doc + const alts = DocListCast(props.DataDoc[props.fieldKey + "-alternates"]); // retrieve alternate documents that may be rendered as alternate images + const altpaths = alts.map(doc => Cast(doc[Doc.LayoutFieldKey(doc)], ImageField, null)?.url).filter(url => url).map(url => this.choosePath(url, props.DataDoc)); // access the primary layout data of the alternate documents + const paths = field ? [this.choosePath(field.url, props.DataDoc), ...altpaths] : altpaths; + if (paths.length) { + url = paths; + } else { + url = [Utils.CorsProxy("http://www.cs.brown.edu/~bcz/noImage.png")]; + image = false; + } + //url = paths.length ? paths : [Utils.CorsProxy("http://www.cs.brown.edu/~bcz/noImage.png")]; + } else { + url = [Utils.CorsProxy("http://www.cs.brown.edu/~bcz/noImage.png")]; + image = false; + } + + const heightToWidth = NumCast(props.DataDoc?._nativeHeight) / NumCast(props.DataDoc?._nativeWidth); + const height = this.props.rowProps.width * heightToWidth; + + if (props.fieldKey === "data") { + if (url !== []) { + const reference = React.createRef<HTMLDivElement>(); + return ( + <div className="collectionSchemaView-cellWrapper" ref={this._focusRef} tabIndex={-1} onPointerDown={this.onPointerDown}> + <div className="collectionSchemaView-cellContents" key={this._document[Id]} ref={reference}> + <img src={url[0]} width={image ? this.props.rowProps.width : "30px"} + height={image ? height : "30px"} /> + </div > + </div> + ); + + } else { + return this.renderCellWithType("image"); + } + } else { + return this.renderCellWithType("image"); + } } } + + + + +@observer +export class CollectionSchemaListCell extends CollectionSchemaCell { + + _overlayDisposer?: () => void; + + private prop: FieldViewProps = { + Document: this.props.rowProps.original, + DataDoc: this.props.rowProps.original, + LibraryPath: [], + dropAction: "alias", + bringToFront: emptyFunction, + rootSelected: returnFalse, + fieldKey: this.props.rowProps.column.id as string, + ContainingCollectionView: this.props.CollectionView, + ContainingCollectionDoc: this.props.CollectionView && this.props.CollectionView.props.Document, + isSelected: returnFalse, + select: emptyFunction, + renderDepth: this.props.renderDepth + 1, + ScreenToLocalTransform: Transform.Identity, + focus: emptyFunction, + active: returnFalse, + whenActiveChanged: emptyFunction, + PanelHeight: returnZero, + PanelWidth: returnZero, + NativeHeight: returnZero, + NativeWidth: returnZero, + addDocTab: this.props.addDocTab, + pinToPres: this.props.pinToPres, + ContentScaling: returnOne, + docFilters: returnEmptyFilter + }; + @observable private _field = this.prop.Document[this.prop.fieldKey]; + @observable private _optionsList = this._field as List<any>; + @observable private _opened = false; + @observable private _text = "select an item"; + @observable private _selectedNum = 0; + + @action + toggleOpened(open: boolean) { + console.log("open: " + open); + this._opened = open; + } + + // @action + // onChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => { + // this._text = e.target.value; + + // // change if its a document + // this._optionsList[this._selectedNum] = this._text; + // } + + @action + onSetValue = (value: string) => { + + + this._text = value; + + // change if its a document + this._optionsList[this._selectedNum] = this._text; + + (this.prop.Document[this.prop.fieldKey] as List<any>).splice(this._selectedNum, 1, value); + + } + + @action + onSelected = (element: string, index: number) => { + this._text = element; + this._selectedNum = index; + } + + onFocus = () => { + this._overlayDisposer?.(); + this._overlayDisposer = OverlayView.Instance.addElement(<DocumentIconContainer />, { x: 0, y: 0 }); + } + + + render() { + + const dragRef: React.RefObject<HTMLDivElement> = React.createRef(); + + let type = "list"; + + let link = false; + let doc = false; + const reference = React.createRef<HTMLDivElement>(); + + if (typeof this._field === "object" && this._optionsList[0]) { + + const options = this._optionsList.map((element, index) => { + + if (element instanceof Doc) { + doc = true; + type = "document"; + if (this.prop.fieldKey.toLowerCase() === "links") { + link = true; + type = "link"; + } + const document = FieldValue(Cast(element, Doc)); + const title = element.title; + return <div + className="collectionSchemaView-dropdownOption" + onPointerDown={(e) => { this.onSelected(StrCast(element.title), index); }} + style={{ padding: "6px" }}> + {title} + </div>; + + } else { + return <div + className="collectionSchemaView-dropdownOption" + onPointerDown={(e) => { this.onSelected(StrCast(element), index); }} + style={{ padding: "6px" }}>{element}</div>; + } + }); + + const plainText = <div style={{ padding: "5.9px" }}>{this._text}</div>; + // const textarea = <textarea onChange={this.onChange} value={this._text} + // onFocus={doc ? this.onFocus : undefined} + // onBlur={doc ? e => this._overlayDisposer?.() : undefined} + // style={{ resize: "none" }} + // placeholder={"select an item"}></textarea>; + + const textarea = <div className="collectionSchemaView-cellContents" + style={{ padding: "5.9px" }} + ref={type === undefined || type === "document" ? this.dropRef : null} key={this.prop.Document[Id]}> + <EditableView + editing={this._isEditing} + isEditingCallback={this.isEditingCallback} + display={"inline"} + contents={this._text} + height={"auto"} + maxHeight={Number(MAX_ROW_HEIGHT)} + GetValue={() => { + return this._text; + }} + SetValue={action((value: string) => { + + // add special for params + this.onSetValue(value); + return true; + })} + /> + </div >; + + //☰ + + const dropdown = <div> + {options} + </div>; + + return ( + <div className="collectionSchemaView-cellWrapper" ref={this._focusRef} tabIndex={-1} onPointerDown={this.onPointerDown}> + <div className="collectionSchemaView-cellContents" key={this._document[Id]} ref={reference}> + <div className="collectionSchemaView-dropDownWrapper"> + <button type="button" className="collectionSchemaView-dropdownButton" onClick={(e) => { this.toggleOpened(!this._opened); }} + style={{ right: "length", position: "relative" }}> + {this._opened ? <FontAwesomeIcon icon="caret-up" size="lg" ></FontAwesomeIcon> + : <FontAwesomeIcon icon="caret-down" size="lg" ></FontAwesomeIcon>} + </button> + <div className="collectionSchemaView-dropdownText"> {link ? plainText : textarea} </div> + </div> + + {this._opened ? dropdown : null} + </div > + </div> + ); + } else { + return this.renderCellWithType("list"); + } + } +} + + + + + @observer export class CollectionSchemaCheckboxCell extends CollectionSchemaCell { @observable private _isChecked: boolean = typeof this.props.rowProps.original[this.props.rowProps.column.id as string] === "boolean" ? BoolCast(this.props.rowProps.original[this.props.rowProps.column.id as string]) : false; diff --git a/src/client/views/collections/CollectionSchemaHeaders.tsx b/src/client/views/collections/CollectionSchemaHeaders.tsx index dae0600b1..efff4db98 100644 --- a/src/client/views/collections/CollectionSchemaHeaders.tsx +++ b/src/client/views/collections/CollectionSchemaHeaders.tsx @@ -2,7 +2,7 @@ import React = require("react"); import { action, observable } from "mobx"; import { observer } from "mobx-react"; import "./CollectionSchemaView.scss"; -import { faPlus, faFont, faHashtag, faAlignJustify, faCheckSquare, faToggleOn, faSortAmountDown, faSortAmountUp, faTimes } from '@fortawesome/free-solid-svg-icons'; +import { faPlus, faFont, faHashtag, faAlignJustify, faCheckSquare, faToggleOn, faSortAmountDown, faSortAmountUp, faTimes, faImage, faListUl, faCalendar } from '@fortawesome/free-solid-svg-icons'; import { library, IconProp } from "@fortawesome/fontawesome-svg-core"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { ColumnType } from "./CollectionSchemaView"; @@ -13,7 +13,7 @@ const higflyout = require("@hig/flyout"); export const { anchorPoints } = higflyout; export const Flyout = higflyout.default; -library.add(faPlus, faFont, faHashtag, faAlignJustify, faCheckSquare, faToggleOn, faFile as any, faSortAmountDown, faSortAmountUp, faTimes); +library.add(faPlus, faFont, faHashtag, faAlignJustify, faCheckSquare, faToggleOn, faFile as any, faSortAmountDown, faSortAmountUp, faTimes, faImage, faListUl, faCalendar); export interface HeaderProps { keyValue: SchemaHeaderField; @@ -33,7 +33,9 @@ export interface HeaderProps { export class CollectionSchemaHeader extends React.Component<HeaderProps> { render() { const icon: IconProp = this.props.keyType === ColumnType.Number ? "hashtag" : this.props.keyType === ColumnType.String ? "font" : - this.props.keyType === ColumnType.Boolean ? "check-square" : this.props.keyType === ColumnType.Doc ? "file" : "align-justify"; + this.props.keyType === ColumnType.Boolean ? "check-square" : this.props.keyType === ColumnType.Doc ? "file" : + this.props.keyType === ColumnType.Image ? "image" : this.props.keyType === ColumnType.List ? "list-ul" : this.props.keyType === ColumnType.Date ? "calendar" : + "align-justify"; return ( <div className="collectionSchemaView-header" style={{ background: this.props.keyValue.color }}> <CollectionSchemaColumnMenu @@ -72,6 +74,16 @@ export class CollectionSchemaAddColumnHeader extends React.Component<AddColumnHe } } + + + + + + + + + + export interface ColumnMenuProps { columnField: SchemaHeaderField; // keyValue: string; @@ -160,10 +172,22 @@ export class CollectionSchemaColumnMenu extends React.Component<ColumnMenuProps> <FontAwesomeIcon icon={"check-square"} size="sm" /> Checkbox </div> + <div className={"columnMenu-option" + (type === ColumnType.List ? " active" : "")} onClick={() => this.changeColumnType(ColumnType.List)}> + <FontAwesomeIcon icon={"list-ul"} size="sm" /> + List + </div> <div className={"columnMenu-option" + (type === ColumnType.Doc ? " active" : "")} onClick={() => this.changeColumnType(ColumnType.Doc)}> <FontAwesomeIcon icon={"file"} size="sm" /> Document </div> + <div className={"columnMenu-option" + (type === ColumnType.Image ? " active" : "")} onClick={() => this.changeColumnType(ColumnType.Image)}> + <FontAwesomeIcon icon={"image"} size="sm" /> + Image + </div> + <div className={"columnMenu-option" + (type === ColumnType.Date ? " active" : "")} onClick={() => this.changeColumnType(ColumnType.Date)}> + <FontAwesomeIcon icon={"calendar"} size="sm" /> + Date + </div> </div> </div > ); @@ -258,7 +282,7 @@ export class CollectionSchemaColumnMenu extends React.Component<ColumnMenuProps> } -interface KeysDropdownProps { +export interface KeysDropdownProps { keyValue: string; possibleKeys: string[]; existingKeys: string[]; @@ -266,9 +290,10 @@ interface KeysDropdownProps { addNew: boolean; onSelect: (oldKey: string, newKey: string, addnew: boolean) => void; setIsEditing: (isEditing: boolean) => void; + width?: string; } @observer -class KeysDropdown extends React.Component<KeysDropdownProps> { +export class KeysDropdown extends React.Component<KeysDropdownProps> { @observable private _key: string = this.props.keyValue; @observable private _searchTerm: string = this.props.keyValue; @observable private _isOpen: boolean = false; @@ -331,17 +356,26 @@ class KeysDropdown extends React.Component<KeysDropdownProps> { renderOptions = (): JSX.Element[] | JSX.Element => { if (!this._isOpen) return <></>; - const keyOptions = this._searchTerm === "" ? this.props.possibleKeys : this.props.possibleKeys.filter(key => key.toUpperCase().indexOf(this._searchTerm.toUpperCase()) > -1); + const searchTerm = this._searchTerm.trim() === "New field" ? "" : this._searchTerm; + + const keyOptions = searchTerm === "" ? this.props.possibleKeys : this.props.possibleKeys.filter(key => key.toUpperCase().indexOf(this._searchTerm.toUpperCase()) > -1); const exactFound = keyOptions.findIndex(key => key.toUpperCase() === this._searchTerm.toUpperCase()) > -1 || this.props.existingKeys.findIndex(key => key.toUpperCase() === this._searchTerm.toUpperCase()) > -1; const options = keyOptions.map(key => { - return <div key={key} className="key-option" onPointerDown={e => e.stopPropagation()} onClick={() => { this.onSelect(key); this.setSearchTerm(""); }}>{key}</div>; + return <div key={key} className="key-option" style={{ + border: "1px solid lightgray", + width: this.props.width, maxWidth: this.props.width, overflowX: "hidden" + }} + onPointerDown={e => e.stopPropagation()} onClick={() => { this.onSelect(key); this.setSearchTerm(""); }}>{key}</div>; }); // if search term does not already exist as a group type, give option to create new group type if (!exactFound && this._searchTerm !== "" && this.props.canAddNew) { - options.push(<div key={""} className="key-option" + options.push(<div key={""} className="key-option" style={{ + border: "1px solid lightgray", + width: this.props.width, maxWidth: this.props.width, overflowX: "hidden" + }} onClick={() => { this.onSelect(this._searchTerm); this.setSearchTerm(""); }}> Create "{this._searchTerm}" key</div>); } @@ -351,10 +385,19 @@ class KeysDropdown extends React.Component<KeysDropdownProps> { render() { return ( - <div className="keys-dropdown"> - <input className="keys-search" ref={this._inputRef} type="text" value={this._searchTerm} placeholder="Column key" onKeyDown={this.onKeyDown} - onChange={e => this.onChange(e.target.value)} onFocus={this.onFocus} onBlur={this.onBlur}></input> - <div className="keys-options-wrapper" onPointerEnter={this.onPointerEnter} onPointerLeave={this.onPointerOut}> + <div className="keys-dropdown" style={{ width: this.props.width, maxWidth: this.props.width, overflowX: "hidden" }}> + <input className="keys-search" //style={{ width: this.props.width, maxWidth: "1000" }} + ref={this._inputRef} type="text" value={this._searchTerm} placeholder="Column key" onKeyDown={this.onKeyDown} + onChange={e => this.onChange(e.target.value)} + onClick={(e) => { + //this._inputRef.current!.select(); + e.stopPropagation(); + }} onFocus={this.onFocus} onBlur={this.onBlur}></input> + <div className="keys-options-wrapper" style={{ + backgroundColor: "white", + width: this.props.width, maxWidth: this.props.width, overflowX: "hidden" + }} + onPointerEnter={this.onPointerEnter} onPointerLeave={this.onPointerOut}> {this.renderOptions()} </div> </div > diff --git a/src/client/views/collections/CollectionSchemaMovableTableHOC.tsx b/src/client/views/collections/CollectionSchemaMovableTableHOC.tsx index b206765e8..b77173b25 100644 --- a/src/client/views/collections/CollectionSchemaMovableTableHOC.tsx +++ b/src/client/views/collections/CollectionSchemaMovableTableHOC.tsx @@ -137,6 +137,7 @@ export interface MovableRowProps { textWrapRow: (doc: Doc) => void; rowWrapped: boolean; dropAction: string; + addDocTab: any; } export class MovableRow extends React.Component<MovableRowProps> { @@ -232,6 +233,7 @@ export class MovableRow extends React.Component<MovableRowProps> { <div className="row-dragger"> <div className="row-option" onClick={undoBatch(() => this.props.removeDoc(this.props.rowInfo.original))}><FontAwesomeIcon icon="trash" size="sm" /></div> <div className="row-option" style={{ cursor: "grab" }} ref={reference} onPointerDown={onItemDown}><FontAwesomeIcon icon="grip-vertical" size="sm" /></div> + <div className="row-option" onClick={() => this.props.addDocTab(this.props.rowInfo.original, "onRight")}><FontAwesomeIcon icon="external-link-alt" size="sm" /></div> </div> {children} </ReactTableDefaults.TrComponent> diff --git a/src/client/views/collections/CollectionSchemaView.scss b/src/client/views/collections/CollectionSchemaView.scss index a24140b48..5226a60f1 100644 --- a/src/client/views/collections/CollectionSchemaView.scss +++ b/src/client/views/collections/CollectionSchemaView.scss @@ -62,10 +62,15 @@ width: calc(100% - 52px); margin-left: 50px; + z-index: 100; + overflow-y: visible; + &.-header { font-size: 12px; height: 30px; box-shadow: none; + z-index: 100; + overflow-y: visible; } .rt-resizable-header-content { @@ -172,27 +177,36 @@ } -.collectionSchemaView-header { +.collectionSchema-header-menu { height: 100%; - color: gray; + z-index: 100; + position: absolute; + background:white; - .collectionSchema-header-menu { + .collectionSchema-header-toggler { + z-index: 100; + width: 100%; height: 100%; + padding: 4px; + letter-spacing: 2px; + text-transform: uppercase; - .collectionSchema-header-toggler { - width: 100%; - height: 100%; - padding: 4px; - letter-spacing: 2px; - text-transform: uppercase; - - svg { - margin-right: 4px; - } + svg { + margin-right: 4px; } } } +.collectionSchemaView-header { + height: 100%; + color: gray; + z-index: 100; + overflow-y: visible; + display: flex; + justify-content: space-between; + flex-wrap: wrap; +} + button.add-column { width: 28px; } @@ -253,13 +267,16 @@ button.add-column { .keys-dropdown { position: relative; - width: 100%; + //width: 100%; + background-color: white; input { border: 2px solid $light-color-secondary; padding: 3px; height: 28px; font-weight: bold; + letter-spacing: "2px"; + text-transform: "uppercase"; &:focus { font-weight: normal; @@ -273,11 +290,14 @@ button.add-column { position: absolute; top: 28px; box-shadow: 0 10px 16px rgba(0, 0, 0, 0.1); + background-color: white; .key-option { - background-color: $light-color; + //background-color: $light-color; + background-color: white; border: 1px solid lightgray; padding: 2px 3px; + overflow-x: hidden; &:not(:first-child) { border-top: 0; @@ -412,6 +432,56 @@ button.add-column { &:hover .collectionSchemaView-cellContents-docExpander { display: block; } + + + .collectionSchemaView-cellContents-document { + display: inline-block; + } + + .collectionSchemaView-cellContents-docButton { + float: right; + width: "15px"; + height: "15px"; + } + + .collectionSchemaView-dropdownWrapper { + + border: grey; + border-style: solid; + border-width: 1px; + height: 100%; + + .collectionSchemaView-dropdownButton { + + //display: inline-block; + float: left; + height: 100%; + + + } + + .collectionSchemaView-dropdownText { + display: inline-block; + //float: right; + height: 100%; + display: "flex"; + font-size: 13; + justify-content: "center"; + align-items: "center"; + } + + } + + .collectionSchemaView-dropdownContainer { + position: absolute; + border: 1px solid rgba(0, 0, 0, 0.04); + box-shadow: 0 16px 24px 2px rgba(0, 0, 0, 0.14); + + .collectionSchemaView-dropdownOption:hover { + background-color: rgba(0, 0, 0, 0.14); + cursor: pointer; + } + } } .collectionSchemaView-cellContents-docExpander { @@ -422,6 +492,7 @@ button.add-column { top: 0; right: 0; background-color: lightgray; + } .doc-drag-over { @@ -429,6 +500,10 @@ button.add-column { } .collectionSchemaView-toolbar { + z-index: 100; +} + +.collectionSchemaView-toolbar { height: 30px; display: flex; justify-content: flex-end; diff --git a/src/client/views/collections/CollectionSchemaView.tsx b/src/client/views/collections/CollectionSchemaView.tsx index 56a2a517c..3c42a2f1c 100644 --- a/src/client/views/collections/CollectionSchemaView.tsx +++ b/src/client/views/collections/CollectionSchemaView.tsx @@ -4,31 +4,27 @@ import { faCog, faPlus, faSortDown, faSortUp, faTable } from '@fortawesome/free- import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { action, computed, observable, untracked } from "mobx"; import { observer } from "mobx-react"; -import ReactTable, { CellInfo, Column, ComponentPropsGetterR, Resize, SortingRule } from "react-table"; +import { Resize } from "react-table"; import "react-table/react-table.css"; -import { Doc, DocListCast, Field, Opt } from "../../../fields/Doc"; -import { Id } from "../../../fields/FieldSymbols"; +import { Doc } from "../../../fields/Doc"; import { List } from "../../../fields/List"; import { listSpec } from "../../../fields/Schema"; -import { SchemaHeaderField } from "../../../fields/SchemaHeaderField"; -import { ComputedField } from "../../../fields/ScriptField"; -import { Cast, FieldValue, NumCast, StrCast, BoolCast } from "../../../fields/Types"; +import { SchemaHeaderField, PastelSchemaPalette } from "../../../fields/SchemaHeaderField"; +import { Cast, NumCast, StrCast } from "../../../fields/Types"; import { Docs, DocumentOptions } from "../../documents/Documents"; -import { CompileScript, Transformer, ts } from "../../util/Scripting"; import { Transform } from "../../util/Transform"; import { undoBatch } from "../../util/UndoManager"; import { COLLECTION_BORDER_WIDTH } from '../../views/globalCssVariables.scss'; -import { ContextMenu } from "../ContextMenu"; import '../DocumentDecorations.scss'; -import { CellProps, CollectionSchemaCell, CollectionSchemaCheckboxCell, CollectionSchemaDocCell, CollectionSchemaNumberCell, CollectionSchemaStringCell } from "./CollectionSchemaCells"; -import { CollectionSchemaAddColumnHeader, CollectionSchemaHeader } from "./CollectionSchemaHeaders"; -import { MovableColumn, MovableRow } from "./CollectionSchemaMovableTableHOC"; +import { KeysDropdown } from "./CollectionSchemaHeaders"; import "./CollectionSchemaView.scss"; import { CollectionSubView } from "./CollectionSubView"; -import { CollectionView } from "./CollectionView"; import { ContentFittingDocumentView } from "../nodes/ContentFittingDocumentView"; import { setupMoveUpEvents, emptyFunction, returnZero, returnOne, returnFalse } from "../../../Utils"; import { SnappingManager } from "../../util/SnappingManager"; +import Measure from "react-measure"; +import { SchemaTable } from "./SchemaTable"; +import { TraceMobx } from "../../../fields/util"; library.add(faCog, faPlus, faSortUp, faSortDown); library.add(faTable); @@ -40,6 +36,9 @@ export enum ColumnType { String, Boolean, Doc, + Image, + List, + Date } // this map should be used for keys that should have a const type of value const columnTypes: Map<string, ColumnType> = new Map([ @@ -62,6 +61,350 @@ export class CollectionSchemaView extends CollectionSubView(doc => doc) { @computed get tableWidth() { return this.props.PanelWidth() - 2 * this.borderWidth - this.DIVIDER_WIDTH - this.previewWidth(); } @computed get borderWidth() { return Number(COLLECTION_BORDER_WIDTH); } + @observable _menuWidth = 0; + @observable _headerOpen = false; + @observable _isOpen = false; + @observable _node: HTMLDivElement | null = null; + @observable _headerIsEditing = false; + @observable _col: any = ""; + @observable _menuHeight = 0; + @observable _pointerX = 0; + @observable _pointerY = 0; + @observable _openTypes: boolean = false; + @computed get menuCoordinates() { + const x = Math.max(0, Math.min(document.body.clientWidth - this._menuWidth, this._pointerX)); + const y = Math.max(0, Math.min(document.body.clientHeight - this._menuHeight, this._pointerY)); + return this.props.ScreenToLocalTransform().transformPoint(x, y); + } + + @observable scale = this.props.ScreenToLocalTransform().Scale; + + @computed get columns() { + return Cast(this.props.Document._schemaHeaders, listSpec(SchemaHeaderField), []); + } + set columns(columns: SchemaHeaderField[]) { + this.props.Document._schemaHeaders = new List<SchemaHeaderField>(columns); + } + + get documentKeys() { + const docs = this.childDocs; + const keys: { [key: string]: boolean } = {}; + // bcz: ugh. this is untracked since otherwise a large collection of documents will blast the server for all their fields. + // then as each document's fields come back, we update the documents _proxies. Each time we do this, the whole schema will be + // invalidated and re-rendered. This workaround will inquire all of the document fields before the options button is clicked. + // then by the time the options button is clicked, all of the fields should be in place. If a new field is added while this menu + // is displayed (unlikely) it won't show up until something else changes. + //TODO Types + untracked(() => docs.map(doc => Doc.GetAllPrototypes(doc).map(proto => Object.keys(proto).forEach(key => keys[key] = false)))); + + this.columns.forEach(key => keys[key.heading] = true); + return Array.from(Object.keys(keys)); + } + @computed get possibleKeys() { return this.documentKeys.filter(key => this.columns.findIndex(existingKey => existingKey.heading.toUpperCase() === key.toUpperCase()) === -1); } + + + componentDidMount() { + document.addEventListener("pointerdown", this.detectClick); + } + + componentWillUnmount() { + document.removeEventListener("pointerdown", this.detectClick); + } + + @action setHeaderIsEditing = (isEditing: boolean) => this._headerIsEditing = isEditing; + + detectClick = (e: PointerEvent): void => { + if (this._node && this._node.contains(e.target as Node)) { + } else { + this._isOpen = false; + this.setHeaderIsEditing(false); + this.closeHeader(); + } + } + + @action + toggleIsOpen = (): void => { + this._isOpen = !this._isOpen; + this.setHeaderIsEditing(this._isOpen); + } + + @action + changeColumnType = (type: ColumnType, col: any): void => { + this._openTypes = false; + this.setColumnType(col, type); + } + + changeColumnSort = (desc: boolean | undefined, col: any): void => { + this.setColumnSort(col, desc); + } + + changeColumnColor = (color: string, col: any): void => { + this.setColumnColor(col, color); + } + + @undoBatch + setColumnType = (columnField: SchemaHeaderField, type: ColumnType): void => { + if (columnTypes.get(columnField.heading)) return; + + const columns = this.columns; + const index = columns.indexOf(columnField); + if (index > -1) { + columnField.setType(NumCast(type)); + columns[index] = columnField; + this.columns = columns; + } + } + + @undoBatch + setColumnColor = (columnField: SchemaHeaderField, color: string): void => { + const columns = this.columns; + const index = columns.indexOf(columnField); + if (index > -1) { + columnField.setColor(color); + columns[index] = columnField; + this.columns = columns; // need to set the columns to trigger rerender + } + } + + @undoBatch + @action + setColumnSort = (columnField: SchemaHeaderField, descending: boolean | undefined) => { + const columns = this.columns; + const index = columns.findIndex(c => c.heading === columnField.heading); + const column = columns[index]; + column.setDesc(descending); + columns[index] = column; + this.columns = columns; + } + + @action + setNode = (node: HTMLDivElement): void => { + node && (this._node = node); + } + + @action + typesDropdownChange = (bool: boolean) => { + this._openTypes = bool; + } + + renderTypes = (col: any) => { + if (columnTypes.get(col.heading)) return (null); + + const type = col.type; + + const anyType = <div className={"columnMenu-option" + (type === ColumnType.Any ? " active" : "")} onClick={() => this.changeColumnType(ColumnType.Any, col)}> + <FontAwesomeIcon icon={"align-justify"} size="sm" /> + Any + </div>; + + const numType = <div className={"columnMenu-option" + (type === ColumnType.Number ? " active" : "")} onClick={() => this.changeColumnType(ColumnType.Number, col)}> + <FontAwesomeIcon icon={"hashtag"} size="sm" /> + Number + </div>; + + const textType = <div className={"columnMenu-option" + (type === ColumnType.String ? " active" : "")} onClick={() => this.changeColumnType(ColumnType.String, col)}> + <FontAwesomeIcon icon={"font"} size="sm" /> + Text + </div>; + + const boolType = <div className={"columnMenu-option" + (type === ColumnType.Boolean ? " active" : "")} onClick={() => this.changeColumnType(ColumnType.Boolean, col)}> + <FontAwesomeIcon icon={"check-square"} size="sm" /> + Checkbox + </div>; + + const listType = <div className={"columnMenu-option" + (type === ColumnType.List ? " active" : "")} onClick={() => this.changeColumnType(ColumnType.List, col)}> + <FontAwesomeIcon icon={"list-ul"} size="sm" /> + List + </div>; + + const docType = <div className={"columnMenu-option" + (type === ColumnType.Doc ? " active" : "")} onClick={() => this.changeColumnType(ColumnType.Doc, col)}> + <FontAwesomeIcon icon={"file"} size="sm" /> + Document + </div>; + + const imageType = <div className={"columnMenu-option" + (type === ColumnType.Image ? " active" : "")} onClick={() => this.changeColumnType(ColumnType.Image, col)}> + <FontAwesomeIcon icon={"image"} size="sm" /> + Image + </div>; + + const dateType = <div className={"columnMenu-option" + (type === ColumnType.Date ? " active" : "")} onClick={() => this.changeColumnType(ColumnType.Date, col)}> + <FontAwesomeIcon icon={"calendar"} size="sm" /> + Date + </div>; + + + const allColumnTypes = <div className="columnMenu-types"> + {anyType} + {numType} + {textType} + {boolType} + {listType} + {docType} + {imageType} + {dateType} + </div>; + + const justColType = type === ColumnType.Any ? anyType : type === ColumnType.Number ? numType : + type === ColumnType.String ? textType : type === ColumnType.Boolean ? boolType : + type === ColumnType.List ? listType : type === ColumnType.Doc ? docType : + type === ColumnType.Date ? dateType : imageType; + + return ( + <div className="collectionSchema-headerMenu-group"> + <div onClick={() => this.typesDropdownChange(!this._openTypes)}> + <label>Column type:</label> + <FontAwesomeIcon icon={"caret-down"} size="sm" style={{ float: "right" }} /> + </div> + {this._openTypes ? allColumnTypes : justColType} + </div > + ); + } + + renderSorting = (col: any) => { + const sort = col.desc; + return ( + <div className="collectionSchema-headerMenu-group"> + <label>Sort by:</label> + <div className="columnMenu-sort"> + <div className={"columnMenu-option" + (sort === true ? " active" : "")} onClick={() => this.changeColumnSort(true, col)}> + <FontAwesomeIcon icon="sort-amount-down" size="sm" /> + Sort descending + </div> + <div className={"columnMenu-option" + (sort === false ? " active" : "")} onClick={() => this.changeColumnSort(false, col)}> + <FontAwesomeIcon icon="sort-amount-up" size="sm" /> + Sort ascending + </div> + <div className="columnMenu-option" onClick={() => this.changeColumnSort(undefined, col)}> + <FontAwesomeIcon icon="times" size="sm" /> + Clear sorting + </div> + </div> + </div> + ); + } + + renderColors = (col: any) => { + const selected = col.color; + + const pink = PastelSchemaPalette.get("pink2"); + const purple = PastelSchemaPalette.get("purple2"); + const blue = PastelSchemaPalette.get("bluegreen1"); + const yellow = PastelSchemaPalette.get("yellow4"); + const red = PastelSchemaPalette.get("red2"); + const gray = "#f1efeb"; + + return ( + <div className="collectionSchema-headerMenu-group"> + <label>Color:</label> + <div className="columnMenu-colors"> + <div className={"columnMenu-colorPicker" + (selected === pink ? " active" : "")} style={{ backgroundColor: pink }} onClick={() => this.changeColumnColor(pink!, col)}></div> + <div className={"columnMenu-colorPicker" + (selected === purple ? " active" : "")} style={{ backgroundColor: purple }} onClick={() => this.changeColumnColor(purple!, col)}></div> + <div className={"columnMenu-colorPicker" + (selected === blue ? " active" : "")} style={{ backgroundColor: blue }} onClick={() => this.changeColumnColor(blue!, col)}></div> + <div className={"columnMenu-colorPicker" + (selected === yellow ? " active" : "")} style={{ backgroundColor: yellow }} onClick={() => this.changeColumnColor(yellow!, col)}></div> + <div className={"columnMenu-colorPicker" + (selected === red ? " active" : "")} style={{ backgroundColor: red }} onClick={() => this.changeColumnColor(red!, col)}></div> + <div className={"columnMenu-colorPicker" + (selected === gray ? " active" : "")} style={{ backgroundColor: gray }} onClick={() => this.changeColumnColor(gray, col)}></div> + </div> + </div> + ); + } + + @undoBatch + @action + changeColumns = (oldKey: string, newKey: string, addNew: boolean) => { + const columns = this.columns; + if (columns === undefined) { + this.columns = new List<SchemaHeaderField>([new SchemaHeaderField(newKey, "f1efeb")]); + } else { + if (addNew) { + columns.push(new SchemaHeaderField(newKey, "f1efeb")); + this.columns = columns; + } else { + const index = columns.map(c => c.heading).indexOf(oldKey); + if (index > -1) { + const column = columns[index]; + column.setHeading(newKey); + columns[index] = column; + this.columns = columns; + } + } + } + } + + @action + openHeader = (col: any, screenx: number, screeny: number) => { + console.log("header opening"); + this._col = col; + this._headerOpen = !this._headerOpen; + this._pointerX = screenx; + this._pointerY = screeny; + } + + @action + closeHeader = () => { this._headerOpen = false; } + + renderKeysDropDown = (col: any) => { + return <KeysDropdown + keyValue={col.heading} + possibleKeys={this.possibleKeys} + existingKeys={this.columns.map(c => c.heading)} + canAddNew={true} + addNew={false} + onSelect={this.changeColumns} + setIsEditing={this.setHeaderIsEditing} + />; + } + + @undoBatch + @action + deleteColumn = (key: string) => { + const columns = this.columns; + if (columns === undefined) { + this.columns = new List<SchemaHeaderField>([]); + } else { + const index = columns.map(c => c.heading).indexOf(key); + if (index > -1) { + columns.splice(index, 1); + this.columns = columns; + } + } + this.closeHeader(); + } + + getPreviewTransform = (): Transform => { + return this.props.ScreenToLocalTransform().translate(- this.borderWidth - NumCast(COLLECTION_BORDER_WIDTH) - this.tableWidth, - this.borderWidth); + } + + @action + onHeaderClick = (e: React.PointerEvent) => { + this.props.active(true); + e.stopPropagation(); + } + + @action + onWheel(e: React.WheelEvent) { + const scale = this.props.ScreenToLocalTransform().Scale; + this.props.active(true) && e.stopPropagation(); + //this.menuCoordinates[0] -= e.screenX / scale; + //this.menuCoordinates[1] -= e.screenY / scale; + } + + @computed get renderMenuContent() { + TraceMobx(); + return <div className="collectionSchema-header-menuOptions"> + <div className="collectionSchema-headerMenu-group"> + <label>Key:</label> + {this.renderKeysDropDown(this._col)} + </div> + {this.renderTypes(this._col)} + {this.renderSorting(this._col)} + {this.renderColors(this._col)} + <div className="collectionSchema-headerMenu-group"> + <button onClick={() => { this.deleteColumn(this._col.heading); }} + >Delete Column</button> + </div> + </div>; + } + private createTarget = (ele: HTMLDivElement) => { this._previewCont = ele; super.CreateDropTarget(ele); @@ -105,14 +448,12 @@ export class CollectionSchemaView extends CollectionSubView(doc => doc) { @computed get previewDocument(): Doc | undefined { return this.previewDoc; } - getPreviewTransform = (): Transform => { - return this.props.ScreenToLocalTransform().translate(- this.borderWidth - this.DIVIDER_WIDTH - this.tableWidth, - this.borderWidth); - } - @computed get dividerDragger() { return this.previewWidth() === 0 ? (null) : - <div className="collectionSchemaView-dividerDragger" onPointerDown={this.onDividerDown} style={{ width: `${this.DIVIDER_WIDTH}px` }} />; + <div className="collectionSchemaView-dividerDragger" + onPointerDown={this.onDividerDown} + style={{ width: `${this.DIVIDER_WIDTH}px` }} />; } @computed @@ -174,6 +515,17 @@ export class CollectionSchemaView extends CollectionSubView(doc => doc) { deleteDocument={this.props.removeDocument} addDocument={this.props.addDocument} dataDoc={this.props.DataDoc} + columns={this.columns} + documentKeys={this.documentKeys} + headerIsEditing={this._headerIsEditing} + openHeader={this.openHeader} + onPointerDown={this.onTablePointerDown} + onResizedChange={this.onResizedChange} + setColumns={this.setColumns} + reorderColumns={this.reorderColumns} + changeColumns={this.changeColumns} + setHeaderIsEditing={this.setHeaderIsEditing} + changeColumnSort={this.setColumnSort} />; } @@ -181,388 +533,33 @@ export class CollectionSchemaView extends CollectionSubView(doc => doc) { public get schemaToolbar() { return <div className="collectionSchemaView-toolbar"> <div className="collectionSchemaView-toolbar-item"> - <div id="preview-schema-checkbox-div"><input type="checkbox" key={"Show Preview"} checked={this.previewWidth() !== 0} onChange={this.toggleExpander} />Show Preview</div> + <div id="preview-schema-checkbox-div"> + <input type="checkbox" + key={"Show Preview"} checked={this.previewWidth() !== 0} + onChange={this.toggleExpander} />Show Preview</div> </div> </div>; } - render() { - 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> - {this.dividerDragger} - {!this.previewWidth() ? (null) : this.previewPanel} - </div>; - } -} - -export interface SchemaTableProps { - Document: Doc; // child doc - dataDoc?: Doc; - PanelHeight: () => number; - PanelWidth: () => number; - childDocs?: Doc[]; - CollectionView: Opt<CollectionView>; - ContainingCollectionView: Opt<CollectionView>; - ContainingCollectionDoc: Opt<Doc>; - fieldKey: string; - renderDepth: number; - deleteDocument: (document: Doc | Doc[]) => boolean; - addDocument: (document: Doc | Doc[]) => boolean; - moveDocument: (document: Doc | Doc[], targetCollection: Doc | undefined, addDocument: (document: Doc | Doc[]) => boolean) => boolean; - ScreenToLocalTransform: () => Transform; - active: (outsideReaction: boolean) => boolean; - onDrop: (e: React.DragEvent<Element>, options: DocumentOptions, completed?: (() => void) | undefined) => void; - addDocTab: (document: Doc, where: string) => boolean; - pinToPres: (document: Doc) => void; - isSelected: (outsideReaction?: boolean) => boolean; - isFocused: (document: Doc) => boolean; - setFocused: (document: Doc) => void; - setPreviewDoc: (document: Doc) => void; -} - -@observer -export class SchemaTable extends React.Component<SchemaTableProps> { - private DIVIDER_WIDTH = 4; - - @observable _headerIsEditing: boolean = false; - @observable _cellIsEditing: boolean = false; - @observable _focusedCell: { row: number, col: number } = { row: 0, col: 0 }; - @observable _openCollections: Array<string> = []; - - @computed get previewWidth() { return () => NumCast(this.props.Document.schemaPreviewWidth); } - @computed get previewHeight() { return () => this.props.PanelHeight() - 2 * this.borderWidth; } - @computed get tableWidth() { return this.props.PanelWidth() - 2 * this.borderWidth - this.DIVIDER_WIDTH - this.previewWidth(); } - - @computed get columns() { - return Cast(this.props.Document.schemaColumns, listSpec(SchemaHeaderField), []); - } - set columns(columns: SchemaHeaderField[]) { - this.props.Document.schemaColumns = new List<SchemaHeaderField>(columns); - } - - @computed get childDocs() { - if (this.props.childDocs) return this.props.childDocs; - - const doc = this.props.dataDoc ? this.props.dataDoc : this.props.Document; - return DocListCast(doc[this.props.fieldKey]); - } - set childDocs(docs: Doc[]) { - const doc = this.props.dataDoc ? this.props.dataDoc : this.props.Document; - doc[this.props.fieldKey] = new List<Doc>(docs); - } - - @computed get textWrappedRows() { - return Cast(this.props.Document.textwrappedSchemaRows, listSpec("string"), []); - } - set textWrappedRows(textWrappedRows: string[]) { - this.props.Document.textwrappedSchemaRows = new List<string>(textWrappedRows); - } - - @computed get resized(): { id: string, value: number }[] { - return this.columns.reduce((resized, shf) => { - (shf.width > -1) && resized.push({ id: shf.heading, value: shf.width }); - return resized; - }, [] as { id: string, value: number }[]); - } - @computed get sorted(): SortingRule[] { - return this.columns.reduce((sorted, shf) => { - shf.desc && sorted.push({ id: shf.heading, desc: shf.desc }); - return sorted; - }, [] as SortingRule[]); - } - - @computed get borderWidth() { return Number(COLLECTION_BORDER_WIDTH); } - @computed get tableColumns(): Column<Doc>[] { - const possibleKeys = this.documentKeys.filter(key => this.columns.findIndex(existingKey => existingKey.heading.toUpperCase() === key.toUpperCase()) === -1); - const columns: Column<Doc>[] = []; - const tableIsFocused = this.props.isFocused(this.props.Document); - const focusedRow = this._focusedCell.row; - const focusedCol = this._focusedCell.col; - const isEditable = !this._headerIsEditing; - - if (this.childDocs.reduce((found, doc) => found || doc.type === "collection", false)) { - columns.push( - { - expander: true, - Header: "", - width: 30, - Expander: (rowInfo) => { - if (rowInfo.original.type === "collection") { - if (rowInfo.isExpanded) return <div className="collectionSchemaView-expander" onClick={() => this.onCloseCollection(rowInfo.original)}><FontAwesomeIcon icon={"sort-up"} size="sm" /></div>; - if (!rowInfo.isExpanded) return <div className="collectionSchemaView-expander" onClick={() => this.onExpandCollection(rowInfo.original)}><FontAwesomeIcon icon={"sort-down"} size="sm" /></div>; - } else { - return null; - } - } - } - ); - } - - const cols = this.columns.map(col => { - const header = <CollectionSchemaHeader - keyValue={col} - possibleKeys={possibleKeys} - existingKeys={this.columns.map(c => c.heading)} - keyType={this.getColumnType(col)} - typeConst={columnTypes.get(col.heading) !== undefined} - onSelect={this.changeColumns} - setIsEditing={this.setHeaderIsEditing} - deleteColumn={this.deleteColumn} - setColumnType={this.setColumnType} - setColumnSort={this.setColumnSort} - setColumnColor={this.setColumnColor} - />; - - return { - Header: <MovableColumn columnRenderer={header} columnValue={col} allColumns={this.columns} reorderColumns={this.reorderColumns} ScreenToLocalTransform={this.props.ScreenToLocalTransform} />, - accessor: (doc: Doc) => doc ? doc[col.heading] : 0, - id: col.heading, - Cell: (rowProps: CellInfo) => { - const rowIndex = rowProps.index; - const columnIndex = this.columns.map(c => c.heading).indexOf(rowProps.column.id!); - const isFocused = focusedRow === rowIndex && focusedCol === columnIndex && tableIsFocused; - - const props: CellProps = { - row: rowIndex, - col: columnIndex, - rowProps: rowProps, - isFocused: isFocused, - changeFocusedCellByIndex: this.changeFocusedCellByIndex, - CollectionView: this.props.CollectionView, - ContainingCollection: this.props.ContainingCollectionView, - Document: this.props.Document, - fieldKey: this.props.fieldKey, - renderDepth: this.props.renderDepth, - addDocTab: this.props.addDocTab, - pinToPres: this.props.pinToPres, - moveDocument: this.props.moveDocument, - setIsEditing: this.setCellIsEditing, - isEditable: isEditable, - setPreviewDoc: this.props.setPreviewDoc, - setComputed: this.setComputed, - getField: this.getField, - }; - - const colType = this.getColumnType(col); - if (colType === ColumnType.Number) return <CollectionSchemaNumberCell {...props} />; - if (colType === ColumnType.String) return <CollectionSchemaStringCell {...props} />; - if (colType === ColumnType.Boolean) return <CollectionSchemaCheckboxCell {...props} />; - if (colType === ColumnType.Doc) return <CollectionSchemaDocCell {...props} />; - return <CollectionSchemaCell {...props} />; - }, - minWidth: 200, - }; - }); - columns.push(...cols); - - columns.push({ - Header: <CollectionSchemaAddColumnHeader createColumn={this.createColumn} />, - accessor: (doc: Doc) => 0, - id: "add", - Cell: (rowProps: CellInfo) => <></>, - width: 28, - resizable: false - }); - return columns; - } - - constructor(props: SchemaTableProps) { - super(props); - // convert old schema columns (list of strings) into new schema columns (list of schema header fields) - const oldSchemaColumns = Cast(this.props.Document.schemaColumns, listSpec("string"), []); - if (oldSchemaColumns && oldSchemaColumns.length && typeof oldSchemaColumns[0] !== "object") { - const newSchemaColumns = oldSchemaColumns.map(i => typeof i === "string" ? new SchemaHeaderField(i, "#f1efeb") : i); - this.props.Document.schemaColumns = new List<SchemaHeaderField>(newSchemaColumns); - } - } - - componentDidMount() { - document.addEventListener("keydown", this.onKeyDown); - } - - componentWillUnmount() { - document.removeEventListener("keydown", this.onKeyDown); - } - - tableAddDoc = (doc: Doc, relativeTo?: Doc, before?: boolean) => { - return Doc.AddDocToList(this.props.Document, this.props.fieldKey, doc, relativeTo, before); - } - - private getTrProps: ComponentPropsGetterR = (state, rowInfo) => { - return !rowInfo ? {} : { - ScreenToLocalTransform: this.props.ScreenToLocalTransform, - addDoc: this.tableAddDoc, - removeDoc: this.props.deleteDocument, - rowInfo, - rowFocused: !this._headerIsEditing && rowInfo.index === this._focusedCell.row && this.props.isFocused(this.props.Document), - textWrapRow: this.toggleTextWrapRow, - rowWrapped: this.textWrappedRows.findIndex(id => rowInfo.original[Id] === id) > -1, - dropAction: StrCast(this.props.Document.childDropAction) - }; - } - - private getTdProps: ComponentPropsGetterR = (state, rowInfo, column, instance) => { - if (!rowInfo || column) return {}; - - const row = rowInfo.index; - //@ts-ignore - const col = this.columns.map(c => c.heading).indexOf(column!.id); - const isFocused = this._focusedCell.row === row && this._focusedCell.col === col && this.props.isFocused(this.props.Document); - // TODO: editing border doesn't work :( - return { - style: { - border: !this._headerIsEditing && isFocused ? "2px solid rgb(255, 160, 160)" : "1px solid #f1efeb" - } - }; - } - @action - onCloseCollection = (collection: Doc): void => { - const index = this._openCollections.findIndex(col => col === collection[Id]); - if (index > -1) this._openCollections.splice(index, 1); - } - - @action onExpandCollection = (collection: Doc) => this._openCollections.push(collection[Id]); - @action setCellIsEditing = (isEditing: boolean) => this._cellIsEditing = isEditing; - @action setHeaderIsEditing = (isEditing: boolean) => this._headerIsEditing = isEditing; - - onPointerDown = (e: React.PointerEvent): void => { - this.props.setFocused(this.props.Document); + onTablePointerDown = (e: React.PointerEvent): void => { + this.setFocused(this.props.Document); if (e.button === 0 && !e.altKey && !e.ctrlKey && !e.metaKey && this.props.isSelected(true)) { e.stopPropagation(); } + this._pointerY = e.screenY; + this._pointerX = e.screenX; } - @action - onKeyDown = (e: KeyboardEvent): void => { - if (!this._cellIsEditing && !this._headerIsEditing && this.props.isFocused(this.props.Document)) {// && this.props.isSelected(true)) { - const direction = e.key === "Tab" ? "tab" : e.which === 39 ? "right" : e.which === 37 ? "left" : e.which === 38 ? "up" : e.which === 40 ? "down" : ""; - this._focusedCell = this.changeFocusedCellByDirection(direction, this._focusedCell.row, this._focusedCell.col); - - const pdoc = FieldValue(this.childDocs[this._focusedCell.row]); - pdoc && this.props.setPreviewDoc(pdoc); - } - } - - changeFocusedCellByDirection = (direction: string, curRow: number, curCol: number) => { - switch (direction) { - case "tab": return { row: (curRow + 1 === this.childDocs.length ? 0 : curRow + 1), col: curCol + 1 === this.columns.length ? 0 : curCol + 1 }; - case "right": return { row: curRow, col: curCol + 1 === this.columns.length ? curCol : curCol + 1 }; - case "left": return { row: curRow, col: curCol === 0 ? curCol : curCol - 1 }; - case "up": return { row: curRow === 0 ? curRow : curRow - 1, col: curCol }; - case "down": return { row: curRow + 1 === this.childDocs.length ? curRow : curRow + 1, col: curCol }; - } - return this._focusedCell; - } - - @action - changeFocusedCellByIndex = (row: number, col: number): void => { - if (this._focusedCell.row !== row || this._focusedCell.col !== col) { - this._focusedCell = { row: row, col: col }; - } - this.props.setFocused(this.props.Document); - } - - @undoBatch - createRow = () => { - this.props.addDocument(Docs.Create.TextDocument("", { title: "", _width: 100, _height: 30 })); - } - - @undoBatch - @action - createColumn = () => { - let index = 0; - let found = this.columns.findIndex(col => col.heading.toUpperCase() === "New field".toUpperCase()) > -1; - while (found) { - index++; - found = this.columns.findIndex(col => col.heading.toUpperCase() === ("New field (" + index + ")").toUpperCase()) > -1; - } - this.columns.push(new SchemaHeaderField(`New field ${index ? "(" + index + ")" : ""}`, "#f1efeb")); - } - - @undoBatch - @action - deleteColumn = (key: string) => { - const columns = this.columns; - if (columns === undefined) { - this.columns = new List<SchemaHeaderField>([]); - } else { - const index = columns.map(c => c.heading).indexOf(key); - if (index > -1) { - columns.splice(index, 1); - this.columns = columns; - } - } - } - - @undoBatch - @action - changeColumns = (oldKey: string, newKey: string, addNew: boolean) => { - const columns = this.columns; - if (columns === undefined) { - this.columns = new List<SchemaHeaderField>([new SchemaHeaderField(newKey, "f1efeb")]); - } else { - if (addNew) { - columns.push(new SchemaHeaderField(newKey, "f1efeb")); - this.columns = columns; - } else { - const index = columns.map(c => c.heading).indexOf(oldKey); - if (index > -1) { - const column = columns[index]; - column.setHeading(newKey); - columns[index] = column; - this.columns = columns; - } - } - } - } - - getColumnType = (column: SchemaHeaderField): ColumnType => { - // added functionality to convert old column type stuff to new column type stuff -syip - if (column.type && column.type !== 0) { - return column.type; - } - if (columnTypes.get(column.heading)) { - column.type = columnTypes.get(column.heading)!; - return columnTypes.get(column.heading)!; - } - const typesDoc = FieldValue(Cast(this.props.Document.schemaColumnTypes, Doc)); - if (!typesDoc) { - column.type = ColumnType.Any; - return ColumnType.Any; - } - column.type = NumCast(typesDoc[column.heading]); - return NumCast(typesDoc[column.heading]); - } - - @undoBatch - setColumnType = (columnField: SchemaHeaderField, type: ColumnType): void => { - if (columnTypes.get(columnField.heading)) return; - - const columns = this.columns; - const index = columns.indexOf(columnField); - if (index > -1) { - columnField.setType(NumCast(type)); - columns[index] = columnField; - this.columns = columns; - } - } - - @undoBatch - setColumnColor = (columnField: SchemaHeaderField, color: string): void => { + onResizedChange = (newResized: Resize[], event: any) => { const columns = this.columns; - const index = columns.indexOf(columnField); - if (index > -1) { - columnField.setColor(color); - columns[index] = columnField; - this.columns = columns; // need to set the columns to trigger rerender - } + newResized.forEach(resized => { + const index = columns.findIndex(c => c.heading === resized.id); + const column = columns[index]; + column.setWidth(resized.value); + columns[index] = column; + }); + this.columns = columns; } @action @@ -581,180 +578,54 @@ export class SchemaTable extends React.Component<SchemaTableProps> { this.columns = columns; } - @undoBatch - @action - setColumnSort = (columnField: SchemaHeaderField, descending: boolean | undefined) => { - const columns = this.columns; - const index = columns.findIndex(c => c.heading === columnField.heading); - const column = columns[index]; - column.setDesc(descending); - columns[index] = column; - this.columns = columns; - } - - get documentKeys() { - const docs = this.childDocs; - const keys: { [key: string]: boolean } = {}; - // bcz: ugh. this is untracked since otherwise a large collection of documents will blast the server for all their fields. - // then as each document's fields come back, we update the documents _proxies. Each time we do this, the whole schema will be - // invalidated and re-rendered. This workaround will inquire all of the document fields before the options button is clicked. - // then by the time the options button is clicked, all of the fields should be in place. If a new field is added while this menu - // is displayed (unlikely) it won't show up until something else changes. - //TODO Types - untracked(() => docs.map(doc => Doc.GetAllPrototypes(doc).map(proto => Object.keys(proto).forEach(key => keys[key] = false)))); - - this.columns.forEach(key => keys[key.heading] = true); - return Array.from(Object.keys(keys)); - } - - @undoBatch - @action - toggleTextwrap = async () => { - const textwrappedRows = Cast(this.props.Document.textwrappedSchemaRows, listSpec("string"), []); - if (textwrappedRows.length) { - this.props.Document.textwrappedSchemaRows = new List<string>([]); + onZoomMenu = (e: React.WheelEvent) => { + this.props.active(true) && e.stopPropagation(); + if (this.menuCoordinates[0] > e.screenX) { + this.menuCoordinates[0] -= e.screenX; //* this.scale; } else { - const docs = DocListCast(this.props.Document[this.props.fieldKey]); - const allRows = docs instanceof Doc ? [docs[Id]] : docs.map(doc => doc[Id]); - this.props.Document.textwrappedSchemaRows = new List<string>(allRows); - } - } - - @action - toggleTextWrapRow = (doc: Doc): void => { - const textWrapped = this.textWrappedRows; - const index = textWrapped.findIndex(id => doc[Id] === id); - - index > -1 ? textWrapped.splice(index, 1) : textWrapped.push(doc[Id]); - - this.textWrappedRows = textWrapped; - } - - @computed - get reactTable() { - const children = this.childDocs; - const hasCollectionChild = children.reduce((found, doc) => found || doc.type === "collection", false); - const expandedRowsList = this._openCollections.map(col => children.findIndex(doc => doc[Id] === col).toString()); - const expanded = {}; - //@ts-ignore - expandedRowsList.forEach(row => expanded[row] = true); - const rerender = [...this.textWrappedRows]; // TODO: get component to rerender on text wrap change without needign to console.log :(((( - - return <ReactTable - style={{ position: "relative" }} - data={children} - page={0} - pageSize={children.length} - showPagination={false} - columns={this.tableColumns} - getTrProps={this.getTrProps} - getTdProps={this.getTdProps} - sortable={false} - TrComponent={MovableRow} - sorted={this.sorted} - expanded={expanded} - 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} dataDoc={undefined} childDocs={undefined} /></div>} - - />; - } - - onResizedChange = (newResized: Resize[], event: any) => { - const columns = this.columns; - newResized.forEach(resized => { - const index = columns.findIndex(c => c.heading === resized.id); - const column = columns[index]; - column.setWidth(resized.value); - columns[index] = column; - }); - this.columns = columns; - } - - onContextMenu = (e: React.MouseEvent): void => { - if (!e.isPropagationStopped() && this.props.Document[Id] !== "mainDoc") { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7 - // ContextMenu.Instance.addItem({ description: "Make DB", event: this.makeDB, icon: "table" }); - ContextMenu.Instance.addItem({ description: "Toggle text wrapping", event: this.toggleTextwrap, icon: "table" }); + this.menuCoordinates[0] += e.screenX; //* this.scale; } - } - - getField = (row: number, col?: number) => { - const docs = this.childDocs; - - row = row % docs.length; - while (row < 0) row += docs.length; - const columns = this.columns; - const doc = docs[row]; - if (col === undefined) { - return doc; - } - if (col >= 0 && col < columns.length) { - const column = this.columns[col].heading; - return doc[column]; - } - return undefined; - } - - createTransformer = (row: number, col: number): Transformer => { - const self = this; - const captures: { [name: string]: Field } = {}; - - const transformer: ts.TransformerFactory<ts.SourceFile> = context => { - return root => { - function visit(node: ts.Node) { - node = ts.visitEachChild(node, visit, context); - if (ts.isIdentifier(node)) { - const isntPropAccess = !ts.isPropertyAccessExpression(node.parent) || node.parent.expression === node; - const isntPropAssign = !ts.isPropertyAssignment(node.parent) || node.parent.name !== node; - if (isntPropAccess && isntPropAssign) { - if (node.text === "$r") { - return ts.createNumericLiteral(row.toString()); - } else if (node.text === "$c") { - return ts.createNumericLiteral(col.toString()); - } else if (node.text === "$") { - if (ts.isCallExpression(node.parent)) { - // captures.doc = self.props.Document; - // captures.key = self.props.fieldKey; - } - } - } - } - - return node; - } - return ts.visitNode(root, visit); - }; - }; - - // const getVars = () => { - // return { capturedVariables: captures }; - // }; - - return { transformer, /*getVars*/ }; - } - - setComputed = (script: string, doc: Doc, field: string, row: number, col: number): boolean => { - script = - `const $ = (row:number, col?:number) => { - if(col === undefined) { - return (doc as any)[key][row + ${row}]; - } - return (doc as any)[key][row + ${row}][(doc as any).schemaColumns[col + ${col}].heading]; - } - return ${script}`; - const compiled = CompileScript(script, { params: { this: Doc.name }, capturedVariables: { doc: this.props.Document, key: this.props.fieldKey }, typecheck: false, transformer: this.createTransformer(row, col) }); - if (compiled.compiled) { - doc[field] = new ComputedField(compiled); - return true; + if (this.menuCoordinates[1] > e.screenY) { + this.menuCoordinates[1] -= e.screenY; //* this.scale; + } else { + this.menuCoordinates[1] += e.screenY; //* this.scale; } - return false; } render() { - return <div className="collectionSchemaView-table" onPointerDown={this.onPointerDown} onWheel={e => this.props.active(true) && e.stopPropagation()} onDrop={e => this.props.onDrop(e, {})} onContextMenu={this.onContextMenu} > - {this.reactTable} - <div className="collectionSchemaView-addRow" onClick={() => this.createRow()}>+ new</div> + TraceMobx(); + const menuContent = this.renderMenuContent; + const menu = <div className="collectionSchema-header-menu" ref={this.setNode} + onWheel={e => this.onZoomMenu(e)} + onPointerDown={e => this.onHeaderClick(e)} + style={{ + position: "fixed", background: "white", + transform: `translate(${this.menuCoordinates[0] / this.scale}px, ${this.menuCoordinates[1] / this.scale}px)` + }}> + <Measure offset onResize={action((r: any) => { + const dim = this.props.ScreenToLocalTransform().inverse().transformDirection(r.offset.width, r.offset.height); + this._menuWidth = dim[0]; this._menuHeight = dim[1]; + })}> + {({ measureRef }) => <div ref={measureRef}> {menuContent} </div>} + </Measure> + </div>; + + 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> + {this.dividerDragger} + {!this.previewWidth() ? (null) : this.previewPanel} + {this._headerOpen ? menu : null} </div>; } }
\ No newline at end of file diff --git a/src/client/views/collections/CollectionStackingView.scss b/src/client/views/collections/CollectionStackingView.scss index 3d8ec2fd5..8fc74a9c6 100644 --- a/src/client/views/collections/CollectionStackingView.scss +++ b/src/client/views/collections/CollectionStackingView.scss @@ -33,8 +33,9 @@ .collectionStackingViewFieldColumn { height: max-content; } + .collectionStackingViewFieldColumnDragging { - height:100%; + height: 100%; } .collectionSchemaView-previewDoc { @@ -425,4 +426,15 @@ .rc-switch-checked .rc-switch-inner { left: 8px; } +} + +@media only screen and (max-device-width: 480px) { + + .collectionStackingView .collectionStackingView-columnDragger, + .collectionMasonryView .collectionStackingView-columnDragger { + width: 0.1; + height: 0.1; + opacity: 0; + font-size: 0; + } }
\ No newline at end of file diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index 4aab43b08..9d8790dda 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -43,27 +43,26 @@ export class CollectionStackingView extends CollectionSubView(StackingDocument) @observable _heightMap = new Map<string, number>(); @observable _cursor: CursorProperty = "grab"; @observable _scroll = 0; // used to force the document decoration to update when scrolling - @computed get sectionHeaders() { return Cast(this.props.Document.sectionHeaders, listSpec(SchemaHeaderField)); } - @computed get pivotField() { return StrCast(this.props.Document._pivotField); } + @computed get columnHeaders() { return Cast(this.layoutDoc._columnHeaders, listSpec(SchemaHeaderField)); } + @computed get pivotField() { return StrCast(this.layoutDoc._pivotField); } @computed get filteredChildren() { return this.childLayoutPairs.filter(pair => pair.layout instanceof Doc).map(pair => pair.layout); } - @computed get xMargin() { return NumCast(this.props.Document._xMargin, 2 * Math.min(this.gridGap, .05 * this.props.PanelWidth())); } - @computed get yMargin() { return Math.max(this.props.Document._showTitle && !this.props.Document._showTitleHover ? 30 : 0, NumCast(this.props.Document._yMargin, 0)); } // 2 * this.gridGap)); } - @computed get gridGap() { return NumCast(this.props.Document._gridGap, 10); } - @computed get isStackingView() { return BoolCast(this.props.Document.singleColumn, true); } + @computed get xMargin() { return NumCast(this.layoutDoc._xMargin, 2 * Math.min(this.gridGap, .05 * this.props.PanelWidth())); } + @computed get yMargin() { return Math.max(this.layoutDoc._showTitle && !this.layoutDoc._showTitleHover ? 30 : 0, NumCast(this.layoutDoc._yMargin, 0)); } // 2 * this.gridGap)); } + @computed get gridGap() { return NumCast(this.layoutDoc._gridGap, 10); } + @computed get isStackingView() { return BoolCast(this.layoutDoc._columnsStack, true); } @computed get numGroupColumns() { return this.isStackingView ? Math.max(1, this.Sections.size + (this.showAddAGroup ? 1 : 0)) : 1; } - @computed get showAddAGroup() { return (this.pivotField && (this.props.Document._chromeStatus !== 'view-mode' && this.props.Document._chromeStatus !== 'disabled')); } + @computed get showAddAGroup() { return (this.pivotField && (this.layoutDoc._chromeStatus !== 'view-mode' && this.layoutDoc._chromeStatus !== 'disabled')); } @computed get columnWidth() { - TraceMobx(); - return Math.min(this.props.PanelWidth() / (this.props as any).ContentScaling() - 2 * this.xMargin, - this.isStackingView ? Number.MAX_VALUE : this.props.Document.columnWidth === -1 ? this.props.PanelWidth() - 2 * this.xMargin : NumCast(this.props.Document.columnWidth, 250)); + return Math.min(this.props.PanelWidth() / this.props.ContentScaling() - 2 * this.xMargin, + this.isStackingView ? Number.MAX_VALUE : this.layoutDoc._columnWidth === -1 ? this.props.PanelWidth() - 2 * this.xMargin : NumCast(this.layoutDoc._columnWidth, 250)); } @computed get NodeWidth() { return this.props.PanelWidth() - this.gridGap; } constructor(props: any) { super(props); - if (this.sectionHeaders === undefined) { - this.props.Document.sectionHeaders = new List<SchemaHeaderField>(); + if (this.columnHeaders === undefined) { + this.layoutDoc._columnHeaders = new List<SchemaHeaderField>(); } } @@ -89,14 +88,14 @@ export class CollectionStackingView extends CollectionSubView(StackingDocument) } get Sections() { - if (!this.pivotField || this.sectionHeaders instanceof Promise) return new Map<SchemaHeaderField, Doc[]>(); + if (!this.pivotField || this.columnHeaders instanceof Promise) return new Map<SchemaHeaderField, Doc[]>(); - if (this.sectionHeaders === undefined) { - setTimeout(() => this.props.Document.sectionHeaders = new List<SchemaHeaderField>(), 0); + if (this.columnHeaders === undefined) { + setTimeout(() => this.layoutDoc._columnHeaders = new List<SchemaHeaderField>(), 0); return new Map<SchemaHeaderField, Doc[]>(); } - const sectionHeaders = Array.from(this.sectionHeaders); - const fields = new Map<SchemaHeaderField, Doc[]>(sectionHeaders.map(sh => [sh, []] as [SchemaHeaderField, []])); + const columnHeaders = Array.from(this.columnHeaders); + const fields = new Map<SchemaHeaderField, Doc[]>(columnHeaders.map(sh => [sh, []] as [SchemaHeaderField, []])); let changed = false; this.filteredChildren.map(d => { const sectionValue = (d[this.pivotField] ? d[this.pivotField] : `NO ${this.pivotField.toUpperCase()} VALUE`) as object; @@ -105,26 +104,26 @@ export class CollectionStackingView extends CollectionSubView(StackingDocument) const castedSectionValue = !isNaN(parsed) ? parsed : sectionValue; // look for if header exists already - const existingHeader = sectionHeaders.find(sh => sh.heading === (castedSectionValue ? castedSectionValue.toString() : `NO ${this.pivotField.toUpperCase()} VALUE`)); + const existingHeader = columnHeaders.find(sh => sh.heading === (castedSectionValue ? castedSectionValue.toString() : `NO ${this.pivotField.toUpperCase()} VALUE`)); if (existingHeader) { fields.get(existingHeader)!.push(d); } else { const newSchemaHeader = new SchemaHeaderField(castedSectionValue ? castedSectionValue.toString() : `NO ${this.pivotField.toUpperCase()} VALUE`); fields.set(newSchemaHeader, [d]); - sectionHeaders.push(newSchemaHeader); + columnHeaders.push(newSchemaHeader); changed = true; } }); // remove all empty columns if hideHeadings is set - if (this.props.Document.hideHeadings) { + if (this.layoutDoc._columnsHideIfEmpty) { Array.from(fields.keys()).filter(key => !fields.get(key)!.length).map(header => { fields.delete(header); - sectionHeaders.splice(sectionHeaders.indexOf(header), 1); + columnHeaders.splice(columnHeaders.indexOf(header), 1); changed = true; }); } - changed && setTimeout(action(() => { if (this.sectionHeaders) { this.sectionHeaders.length = 0; this.sectionHeaders.push(...sectionHeaders); } }), 0); + changed && setTimeout(action(() => { if (this.columnHeaders) { this.columnHeaders.length = 0; this.columnHeaders.push(...columnHeaders); } }), 0); return fields; } @@ -136,7 +135,7 @@ export class CollectionStackingView extends CollectionSubView(StackingDocument) let wid = this.columnWidth / (this.isStackingView ? this.numGroupColumns : 1); if (!layoutDoc._fitWidth && nw && nh) { const aspect = nw && nh ? nh / nw : 1; - if (!(this.props.Document.fillColumn)) wid = Math.min(layoutDoc[WidthSym](), wid); + if (!(this.layoutDoc._columnsFill)) wid = Math.min(layoutDoc[WidthSym](), wid); return wid * aspect; } return layoutDoc._fitWidth ? wid * NumCast(layoutDoc.scrollHeight, nh) / (nw || 1) : layoutDoc[HeightSym](); @@ -147,7 +146,7 @@ export class CollectionStackingView extends CollectionSubView(StackingDocument) // reset section headers when a new filter is inputted this._pivotFieldDisposer = reaction( () => this.pivotField, - () => this.props.Document.sectionHeaders = new List() + () => this.layoutDoc._columnHeaders = new List() ); } componentWillUnmount() { @@ -211,7 +210,7 @@ export class CollectionStackingView extends CollectionSubView(StackingDocument) fitToBox={false} dontRegisterView={this.props.dontRegisterView} rootSelected={this.rootSelected} - dropAction={StrCast(this.props.Document.childDropAction) as dropActionType} + dropAction={StrCast(this.layoutDoc.childDropAction) as dropActionType} onClick={this.onChildClickHandler} onDoubleClick={this.onChildDoubleClickHandler} ScreenToLocalTransform={dxf} @@ -236,7 +235,7 @@ export class CollectionStackingView extends CollectionSubView(StackingDocument) if (!d) return 0; const layoutDoc = Doc.Layout(d, this.props.ChildLayoutTemplate?.()); const nw = NumCast(layoutDoc._nativeWidth); - return Math.min(nw && !this.props.Document.fillColumn ? d[WidthSym]() : Number.MAX_VALUE, this.columnWidth / this.numGroupColumns); + return Math.min(nw && !this.layoutDoc._columnsFill ? d[WidthSym]() : Number.MAX_VALUE, this.columnWidth / this.numGroupColumns); } getDocHeight(d?: Doc) { if (!d) return 0; @@ -246,7 +245,7 @@ export class CollectionStackingView extends CollectionSubView(StackingDocument) let wid = this.columnWidth / (this.isStackingView ? this.numGroupColumns : 1); if (!layoutDoc._fitWidth && nw && nh) { const aspect = nw && nh ? nh / nw : 1; - if (!(this.props.Document.fillColumn)) wid = Math.min(layoutDoc[WidthSym](), wid); + if (!(this.layoutDoc._columnsFill)) wid = Math.min(layoutDoc[WidthSym](), wid); return wid * aspect; } return layoutDoc._fitWidth ? !nh ? this.props.PanelHeight() - 2 * this.yMargin : @@ -259,7 +258,7 @@ export class CollectionStackingView extends CollectionSubView(StackingDocument) } @action onDividerMove = (e: PointerEvent, down: number[], delta: number[]) => { - this.layoutDoc.columnWidth = Math.max(10, this.columnWidth + delta[0]); + this.layoutDoc._columnWidth = Math.max(10, this.columnWidth + delta[0]); return false; } @@ -341,7 +340,7 @@ export class CollectionStackingView extends CollectionSubView(StackingDocument) this.refList.push(ref); const doc = this.props.DataDoc && this.props.DataDoc.layout === this.layoutDoc ? this.props.DataDoc : this.layoutDoc; this.observer = new _global.ResizeObserver(action((entries: any) => { - if (this.props.Document._autoHeight && ref && this.refList.length && !SnappingManager.GetIsDragging()) { + if (this.layoutDoc._autoHeight && ref && this.refList.length && !SnappingManager.GetIsDragging()) { Doc.Layout(doc)._height = Math.min(1200, Math.max(...this.refList.map(r => Number(getComputedStyle(r).height.replace("px", ""))))); } })); @@ -388,7 +387,7 @@ export class CollectionStackingView extends CollectionSubView(StackingDocument) this.refList.push(ref); const doc = this.props.DataDoc && this.props.DataDoc.layout === this.layoutDoc ? this.props.DataDoc : this.layoutDoc; this.observer = new _global.ResizeObserver(action((entries: any) => { - if (this.props.Document._autoHeight && ref && this.refList.length && !SnappingManager.GetIsDragging()) { + if (this.layoutDoc._autoHeight && ref && this.refList.length && !SnappingManager.GetIsDragging()) { Doc.Layout(doc)._height = this.refList.reduce((p, r) => p + Number(getComputedStyle(r).height.replace("px", "")), 0); } })); @@ -411,9 +410,9 @@ export class CollectionStackingView extends CollectionSubView(StackingDocument) @action addGroup = (value: string) => { - if (value && this.sectionHeaders) { + if (value && this.columnHeaders) { const schemaHdrField = new SchemaHeaderField(value); - this.sectionHeaders.push(schemaHdrField); + this.columnHeaders.push(schemaHdrField); DocUtils.addFieldEnumerations(undefined, this.pivotField, [{ title: value, _backgroundColor: schemaHdrField.color }]); return true; } @@ -421,22 +420,22 @@ export class CollectionStackingView extends CollectionSubView(StackingDocument) } sortFunc = (a: [SchemaHeaderField, Doc[]], b: [SchemaHeaderField, Doc[]]): 1 | -1 => { - const descending = BoolCast(this.props.Document.stackingHeadersSortDescending); + const descending = StrCast(this.layoutDoc._columnsSort) === "descending"; const firstEntry = descending ? b : a; const secondEntry = descending ? a : b; return firstEntry[0].heading > secondEntry[0].heading ? 1 : -1; } onToggle = (checked: Boolean) => { - this.props.Document._chromeStatus = checked ? "collapsed" : "view-mode"; + this.layoutDoc._chromeStatus = checked ? "collapsed" : "view-mode"; } onContextMenu = (e: React.MouseEvent): void => { // need to test if propagation has stopped because GoldenLayout forces a parallel react hierarchy to be created for its top-level layout if (!e.isPropagationStopped()) { const subItems: ContextMenuProps[] = []; - subItems.push({ description: `${this.props.Document.fillColumn ? "Variable Size" : "Autosize"} Column`, event: () => this.props.Document.fillColumn = !this.props.Document.fillColumn, icon: "plus" }); - subItems.push({ description: `${this.Document._autoHeight ? "Variable Height" : "Auto Height"}`, event: () => this.layoutDoc._autoHeight = !this.layoutDoc._autoHeight, icon: "plus" }); + subItems.push({ description: `${this.layoutDoc._columnsFill ? "Variable Size" : "Autosize"} Column`, event: () => this.layoutDoc._columnsFill = !this.layoutDoc._columnsFill, icon: "plus" }); + subItems.push({ description: `${this.layoutDoc._autoHeight ? "Variable Height" : "Auto Height"}`, event: () => this.layoutDoc._autoHeight = !this.layoutDoc._autoHeight, icon: "plus" }); ContextMenu.Instance.addItem({ description: "Options...", subitems: subItems, icon: "eye" }); } } @@ -446,7 +445,7 @@ export class CollectionStackingView extends CollectionSubView(StackingDocument) let sections = [[undefined, this.filteredChildren] as [SchemaHeaderField | undefined, Doc[]]]; if (this.pivotField) { const entries = Array.from(this.Sections.entries()); - sections = entries.sort(this.sortFunc); + sections = this.layoutDoc._columnsSort ? entries.sort(this.sortFunc) : entries; } return sections.map((section, i) => this.isStackingView ? this.sectionStacking(section[0], section[1]) : this.sectionMasonry(section[0], section[1], i === 0)); } @@ -489,14 +488,14 @@ export class CollectionStackingView extends CollectionSubView(StackingDocument) style={{ width: !this.isStackingView ? "100%" : this.columnWidth / this.numGroupColumns - 10, marginTop: 10 }}> <EditableView {...editableViewProps} /> </div>} - {this.props.Document._chromeStatus !== 'disabled' && this.props.isSelected() ? <Switch + {this.layoutDoc._chromeStatus !== 'disabled' && this.props.isSelected() ? <Switch onChange={this.onToggle} onClick={this.onToggle} - defaultChecked={this.props.Document._chromeStatus !== 'view-mode'} + defaultChecked={this.layoutDoc._chromeStatus !== 'view-mode'} checkedChildren="edit" unCheckedChildren="view" /> : null} </div> </div> ); } -}
\ No newline at end of file +} diff --git a/src/client/views/collections/CollectionStackingViewFieldColumn.tsx b/src/client/views/collections/CollectionStackingViewFieldColumn.tsx index b60ed853b..2f4a25bfe 100644 --- a/src/client/views/collections/CollectionStackingViewFieldColumn.tsx +++ b/src/client/views/collections/CollectionStackingViewFieldColumn.tsx @@ -96,8 +96,8 @@ export class CollectionStackingViewFieldColumn extends React.Component<CSVFieldC const key = StrCast(this.props.parent.props.Document._pivotField); const castedValue = this.getValue(value); if (castedValue) { - if (this.props.parent.sectionHeaders) { - if (this.props.parent.sectionHeaders.map(i => i.heading).indexOf(castedValue.toString()) > -1) { + if (this.props.parent.columnHeaders) { + if (this.props.parent.columnHeaders.map(i => i.heading).indexOf(castedValue.toString()) > -1) { return false; } } @@ -148,9 +148,9 @@ export class CollectionStackingViewFieldColumn extends React.Component<CSVFieldC deleteColumn = () => { const key = StrCast(this.props.parent.props.Document._pivotField); this.props.docList.forEach(d => d[key] = undefined); - if (this.props.parent.sectionHeaders && this.props.headingObject) { - const index = this.props.parent.sectionHeaders.indexOf(this.props.headingObject); - this.props.parent.sectionHeaders.splice(index, 1); + if (this.props.parent.columnHeaders && this.props.headingObject) { + const index = this.props.parent.columnHeaders.indexOf(this.props.headingObject); + this.props.parent.columnHeaders.splice(index, 1); } } @@ -168,7 +168,7 @@ export class CollectionStackingViewFieldColumn extends React.Component<CSVFieldC startDrag = (e: PointerEvent, down: number[], delta: number[]) => { const alias = Doc.MakeAlias(this.props.parent.props.Document); - alias._width = this.props.parent.props.PanelWidth() / (Cast(this.props.parent.props.Document.sectionHeaders, listSpec(SchemaHeaderField))?.length || 1); + alias._width = this.props.parent.props.PanelWidth() / (Cast(this.props.parent.columnHeaders, listSpec(SchemaHeaderField))?.length || 1); alias._pivotField = undefined; const key = StrCast(this.props.parent.props.Document._pivotField); let value = this.getValue(this._heading); @@ -259,8 +259,8 @@ export class CollectionStackingViewFieldColumn extends React.Component<CSVFieldC } }, icon: "compress-arrows-alt" })); - layoutItems.push({ description: ":freeform", event: () => this.props.parent.props.addDocument(Docs.Create.FreeformDocument([], { _width: 200, _height: 200, _LODdisable: true })), icon: "compress-arrows-alt" }); - layoutItems.push({ description: ":carousel", event: () => this.props.parent.props.addDocument(Docs.Create.CarouselDocument([], { _width: 400, _height: 200, _LODdisable: true })), icon: "compress-arrows-alt" }); + layoutItems.push({ description: ":freeform", event: () => this.props.parent.props.addDocument(Docs.Create.FreeformDocument([], { _width: 200, _height: 200 })), icon: "compress-arrows-alt" }); + layoutItems.push({ description: ":carousel", event: () => this.props.parent.props.addDocument(Docs.Create.CarouselDocument([], { _width: 400, _height: 200 })), icon: "compress-arrows-alt" }); layoutItems.push({ description: ":columns", event: () => this.props.parent.props.addDocument(Docs.Create.MulticolumnDocument([], { _width: 200, _height: 200 })), icon: "compress-arrows-alt" }); layoutItems.push({ description: ":image", event: () => this.props.parent.props.addDocument(Docs.Create.ImageDocument("http://www.cs.brown.edu/~bcz/face.gif", { _width: 200, _height: 200 })), icon: "compress-arrows-alt" }); @@ -359,10 +359,10 @@ export class CollectionStackingViewFieldColumn extends React.Component<CSVFieldC background: this._background }} ref={this.createColumnDropRef} onPointerEnter={this.pointerEntered} onPointerLeave={this.pointerLeave}> - {this.props.parent.Document.hideHeadings ? (null) : headingView} + {this.props.parent.Document._columnsHideIfEmpty ? (null) : headingView} { this.collapsed ? (null) : - <div> + <div style={{ marginTop: 5 }}> <div key={`${heading}-stack`} className={`collectionStackingView-masonry${singleColumn ? "Single" : "Grid"}`} style={{ padding: singleColumn ? `${columnYMargin}px ${0}px ${style.yMargin}px ${0}px` : `${columnYMargin}px ${0}px`, diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index 00d6d59c8..ed8535ecb 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -1,15 +1,14 @@ import { action, computed, IReactionDisposer, reaction } from "mobx"; import { basename } from 'path'; import CursorField from "../../../fields/CursorField"; -import { Doc, Opt } from "../../../fields/Doc"; +import { Doc, Opt, Field } from "../../../fields/Doc"; import { Id } from "../../../fields/FieldSymbols"; import { List } from "../../../fields/List"; import { listSpec } from "../../../fields/Schema"; import { ScriptField } from "../../../fields/ScriptField"; import { WebField } from "../../../fields/URLField"; -import { Cast, ScriptCast, NumCast } from "../../../fields/Types"; +import { Cast, ScriptCast, NumCast, StrCast } from "../../../fields/Types"; import { GestureUtils } from "../../../pen-gestures/GestureUtils"; -import { Upload } from "../../../server/SharedMediaTypes"; import { Utils, returnFalse, returnEmptyFilter } from "../../../Utils"; import { DocServer } from "../../DocServer"; import { Networking } from "../../Network"; @@ -19,6 +18,7 @@ import { undoBatch, UndoManager } from "../../util/UndoManager"; import { DocComponent } from "../DocComponent"; import { FieldViewProps } from "../nodes/FieldView"; import React = require("react"); +import * as rp from 'request-promise'; export interface CollectionViewProps extends FieldViewProps { addDocument: (document: Doc | Doc[]) => boolean; @@ -103,8 +103,7 @@ export function CollectionSubView<T, X>(schemaCtor: (doc: Doc) => T, moreProps?: } docFilters = () => { return this.props.ignoreFields?.includes("_docFilters") ? [] : - this.props.docFilters !== returnEmptyFilter ? this.props.docFilters() : - Cast(this.props.Document._docFilters, listSpec("string"), []); + [...this.props.docFilters(), ...Cast(this.props.Document._docFilters, listSpec("string"), [])]; } @computed get childDocs() { const docFilters = this.docFilters(); @@ -136,8 +135,12 @@ export function CollectionSubView<T, X>(schemaCtor: (doc: Doc) => T, moreProps?: const filteredDocs = docFilters.length && !this.props.dontRegisterView ? childDocs.filter(d => { for (const facetKey of Object.keys(filterFacets)) { const facet = filterFacets[facetKey]; - const satisfiesFacet = Object.keys(facet).some(value => - (facet[value] === "x") !== Doc.matchFieldValue(d, facetKey, value)); + const satisfiesFacet = Object.keys(facet).some(value => { + if (facet[value] === "match") { + return d[facetKey] === undefined || Field.toString(d[facetKey] as Field).includes(value); + } + return (facet[value] === "x") !== Doc.matchFieldValue(d, facetKey, value); + }); if (!satisfiesFacet) { return false; } @@ -208,7 +211,6 @@ export function CollectionSubView<T, X>(schemaCtor: (doc: Doc) => T, moreProps?: addDocument = (doc: Doc | Doc[]) => this.props.addDocument(doc); - @undoBatch @action protected onInternalDrop(e: Event, de: DragManager.DropEvent): boolean { const docDragData = de.complete.docDragData; @@ -222,7 +224,7 @@ export function CollectionSubView<T, X>(schemaCtor: (doc: Doc) => T, moreProps?: const movedDocs = docDragData.droppedDocuments.filter((d, i) => docDragData.draggedDocuments[i] === d); const addedDocs = docDragData.droppedDocuments.filter((d, i) => docDragData.draggedDocuments[i] !== d); const res = addedDocs.length ? this.addDocument(addedDocs) : true; - added = movedDocs.length ? docDragData.moveDocument(movedDocs, this.props.Document, de.embedKey || !this.props.isAnnotationOverlay ? this.addDocument : returnFalse) : res; + added = movedDocs.length ? docDragData.moveDocument(movedDocs, this.props.Document, Doc.AreProtosEqual(Cast(movedDocs[0].annotationOn, Doc, null), this.props.Document) || de.embedKey || !this.props.isAnnotationOverlay ? this.addDocument : returnFalse) : res; } else { added = this.addDocument(docDragData.droppedDocuments); } @@ -235,21 +237,7 @@ export function CollectionSubView<T, X>(schemaCtor: (doc: Doc) => T, moreProps?: } return false; } - readUploadedFileAsText = (inputFile: File) => { - const temporaryFileReader = new FileReader(); - - return new Promise((resolve, reject) => { - temporaryFileReader.onerror = () => { - temporaryFileReader.abort(); - reject(new DOMException("Problem parsing input file.")); - }; - temporaryFileReader.onload = () => { - resolve(temporaryFileReader.result); - }; - temporaryFileReader.readAsText(inputFile); - }); - } @undoBatch @action protected async onExternalDrop(e: React.DragEvent, options: DocumentOptions, completed?: () => void) { @@ -268,8 +256,7 @@ export function CollectionSubView<T, X>(schemaCtor: (doc: Doc) => T, moreProps?: e.stopPropagation(); e.preventDefault(); - const { addDocument } = this; - if (!addDocument) { + if (!this.addDocument) { alert("this.props.addDocument does not exist. Aborting drop operation."); return; } @@ -283,14 +270,14 @@ export function CollectionSubView<T, X>(schemaCtor: (doc: Doc) => T, moreProps?: DocServer.GetRefField(docid).then(f => { if (f instanceof Doc) { if (options.x || options.y) { f.x = options.x; f.y = options.y; } // should be in CollectionFreeFormView - (f instanceof Doc) && addDocument(f); + (f instanceof Doc) && this.addDocument(f); } }); } else { - addDocument(Docs.Create.WebDocument(href, { ...options, title: href })); + this.addDocument(Docs.Create.WebDocument(href, { ...options, title: href })); } } else if (text) { - addDocument(Docs.Create.TextDocument(text, { ...options, _width: 100, _height: 25 })); + this.addDocument(Docs.Create.TextDocument(text, { ...options, _width: 100, _height: 25 })); } return; } @@ -310,7 +297,7 @@ export function CollectionSubView<T, X>(schemaCtor: (doc: Doc) => T, moreProps?: if (source.startsWith("http")) { const doc = Docs.Create.ImageDocument(source, { ...options, _width: 300 }); ImageUtils.ExtractExif(doc); - addDocument(doc); + this.addDocument(doc); } return; } else { @@ -341,7 +328,7 @@ export function CollectionSubView<T, X>(schemaCtor: (doc: Doc) => T, moreProps?: const rect = "getBoundingClientRect" in focusNode ? focusNode.getBoundingClientRect() : focusNode?.parentElement.getBoundingClientRect(); const x = (rect?.x || 0); const y = NumCast(srcWeb._scrollTop) + (rect?.y || 0); - const anchor = Docs.Create.FreeformDocument([], { _LODdisable: true, _backgroundColor: "transparent", _width: 25, _height: 25, x, y, annotationOn: srcWeb }); + const anchor = Docs.Create.FreeformDocument([], { _backgroundColor: "transparent", _width: 25, _height: 25, x, y, annotationOn: srcWeb }); anchor.context = srcWeb; const key = Doc.LayoutFieldKey(srcWeb); Doc.AddDocToList(srcWeb, key + "-annotations", anchor); @@ -355,9 +342,9 @@ export function CollectionSubView<T, X>(schemaCtor: (doc: Doc) => T, moreProps?: } if (text) { - if (text.includes("www.youtube.com/watch")) { + if (text.includes("www.youtube.com/watch") || text.includes("www.youtube.com/embed")) { const url = text.replace("youtube.com/watch?v=", "youtube.com/embed/").split("&")[0]; - addDocument(Docs.Create.VideoDocument(url, { + this.addDocument(Docs.Create.VideoDocument(url, { ...options, title: url, _width: 400, @@ -400,9 +387,9 @@ export function CollectionSubView<T, X>(schemaCtor: (doc: Doc) => T, moreProps?: const item = e.dataTransfer.items[i]; if (item.kind === "string" && item.type.includes("uri")) { const stringContents = await new Promise<string>(resolve => item.getAsString(resolve)); - const type = "html";// (await rp.head(Utils.CorsProxy(stringContents)))["content-type"]; + const type = (await rp.head(Utils.CorsProxy(stringContents)))["content-type"]; if (type) { - const doc = await DocUtils.DocumentFromType(type, stringContents, options); + const doc = await DocUtils.DocumentFromType(type, Utils.CorsProxy(stringContents), options); doc && generatedDocuments.push(doc); } } @@ -410,10 +397,10 @@ export function CollectionSubView<T, X>(schemaCtor: (doc: Doc) => T, moreProps?: const file = item.getAsFile(); file?.type && files.push(file); - file?.type === "application/json" && this.readUploadedFileAsText(file).then(result => { + file?.type === "application/json" && Utils.readUploadedFileAsText(file).then(result => { console.log(result); const json = JSON.parse(result as string); - addDocument(Docs.Create.TreeDocument( + this.addDocument(Docs.Create.TreeDocument( json["rectangular-puzzle"].crossword.clues[0].clue.map((c: any) => { const label = Docs.Create.LabelDocument({ title: c["#text"], _width: 120, _height: 20 }); const proto = Doc.GetProto(label); @@ -425,38 +412,18 @@ export function CollectionSubView<T, X>(schemaCtor: (doc: Doc) => T, moreProps?: }); } } - for (const { source: { name, type }, result } of await Networking.UploadFilesToServer(files)) { - if (result instanceof Error) { - alert(`Upload failed: ${result.message}`); - return; - } - const full = { ...options, _width: 400, title: name }; - const pathname = Utils.prepend(result.accessPaths.agnostic.client); - const doc = await DocUtils.DocumentFromType(type, pathname, full); - if (!doc) { - continue; - } - const proto = Doc.GetProto(doc); - proto.text = result.rawText; - proto.fileUpload = basename(pathname).replace("upload_", "").replace(/\.[a-z0-9]*$/, ""); - if (Upload.isImageInformation(result)) { - proto["data-nativeWidth"] = (result.nativeWidth > result.nativeHeight) ? 400 * result.nativeWidth / result.nativeHeight : 400; - proto["data-nativeHeight"] = (result.nativeWidth > result.nativeHeight) ? 400 : 400 / (result.nativeWidth / result.nativeHeight); - proto.contentSize = result.contentSize; - } - generatedDocuments.push(doc); - } + generatedDocuments.push(...await DocUtils.uploadFilesToDocs(files, options)); if (generatedDocuments.length) { const set = generatedDocuments.length > 1 && generatedDocuments.map(d => DocUtils.iconify(d)); if (set) { - addDocument(DocUtils.pileup(generatedDocuments, options.x!, options.y!)!); + this.addDocument(DocUtils.pileup(generatedDocuments, options.x!, options.y!)!); } else { - generatedDocuments.forEach(addDocument); + generatedDocuments.forEach(this.addDocument); } completed?.(); } else { if (text && !text.includes("https://")) { - addDocument(Docs.Create.TextDocument(text, { ...options, _width: 400, _height: 315 })); + this.addDocument(Docs.Create.TextDocument(text, { ...options, _width: 400, _height: 315 })); } } batch.end(); @@ -473,3 +440,4 @@ import { DocumentType } from "../../documents/DocumentTypes"; import { FormattedTextBox, GoogleRef } from "../nodes/formattedText/FormattedTextBox"; import { CollectionView } from "./CollectionView"; import { SelectionManager } from "../../util/SelectionManager"; + diff --git a/src/client/views/collections/CollectionTreeView.scss b/src/client/views/collections/CollectionTreeView.scss index 2aac81146..50f0534bd 100644 --- a/src/client/views/collections/CollectionTreeView.scss +++ b/src/client/views/collections/CollectionTreeView.scss @@ -82,8 +82,6 @@ text-overflow: ellipsis; white-space: pre-wrap; min-width: 10px; - // width:100%;//width: max-content; - } .treeViewItem-openRight { @@ -100,6 +98,7 @@ border-left: dashed 1px #00000042; } +.treeViewItem-header-editing, .treeViewItem-header { border: transparent 1px solid; display: flex; diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index 68dc0ced2..620b977fa 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -13,7 +13,7 @@ import { Docs, DocUtils } from '../../documents/Documents'; import { DocumentType } from "../../documents/DocumentTypes"; import { DocumentManager } from '../../util/DocumentManager'; import { SnappingManager } from '../../util/SnappingManager'; -import { DragManager, dropActionType, SetupDrag } from "../../util/DragManager"; +import { DragManager, dropActionType } from "../../util/DragManager"; import { Scripting } from '../../util/Scripting'; import { SelectionManager } from '../../util/SelectionManager'; import { Transform } from '../../util/Transform'; @@ -55,7 +55,7 @@ export interface TreeViewProps { ScreenToLocalTransform: () => Transform; backgroundColor?: (doc: Doc) => string | undefined; outerXf: () => { translateX: number, translateY: number }; - treeViewId: Doc; + treeViewDoc: Doc; parentKey: string; active: (outsideReaction?: boolean) => boolean; treeViewHideHeaderFields: () => boolean; @@ -76,31 +76,32 @@ export interface TreeViewProps { * treeViewExpandedView : name of field whose contents are being displayed as the document's subtree */ class TreeView extends React.Component<TreeViewProps> { - static _editTitleScript: ScriptField | undefined; + private _editTitleScript: ScriptField | undefined; private _header?: React.RefObject<HTMLDivElement> = React.createRef(); private _treedropDisposer?: DragManager.DragDropDisposer; private _dref = React.createRef<HTMLDivElement>(); private _tref = React.createRef<HTMLDivElement>(); private _docRef = React.createRef<DocumentView>(); + private _uniqueId = Utils.GenerateGuid(); + private _editMaxWidth: number | string = 0; + get doc() { return this.props.document; } get noviceMode() { return BoolCast(Doc.UserDoc().noviceMode, false); } - get displayName() { return "TreeView(" + this.props.document.title + ")"; } // this makes mobx trace() statements more descriptive - get defaultExpandedView() { return this.childDocs ? this.fieldKey : StrCast(this.props.document.defaultExpandedView, this.noviceMode ? "layout" : "fields"); } + get displayName() { return "TreeView(" + this.doc.title + ")"; } // this makes mobx trace() statements more descriptive + get defaultExpandedView() { return this.childDocs ? this.fieldKey : StrCast(this.doc.defaultExpandedView, this.noviceMode ? "layout" : "fields"); } @observable _overrideTreeViewOpen = false; // override of the treeViewOpen field allowing the display state to be independent of the document's state - set treeViewOpen(c: boolean) { if (this.props.treeViewPreventOpen) this._overrideTreeViewOpen = c; else this.props.document.treeViewOpen = this._overrideTreeViewOpen = c; } - @computed get treeViewOpen() { return (!this.props.treeViewPreventOpen && !this.props.document.treeViewPreventOpen && BoolCast(this.props.document.treeViewOpen)) || this._overrideTreeViewOpen; } - @computed get treeViewExpandedView() { return StrCast(this.props.document.treeViewExpandedView, this.defaultExpandedView); } + set treeViewOpen(c: boolean) { if (this.props.treeViewPreventOpen) this._overrideTreeViewOpen = c; else this.doc.treeViewOpen = this._overrideTreeViewOpen = c; } + @computed get treeViewOpen() { return (!this.props.treeViewPreventOpen && !this.doc.treeViewPreventOpen && BoolCast(this.doc.treeViewOpen)) || this._overrideTreeViewOpen; } + @computed get treeViewExpandedView() { return StrCast(this.doc.treeViewExpandedView, this.defaultExpandedView); } @computed get MAX_EMBED_HEIGHT() { return NumCast(this.props.containingCollection.maxEmbedHeight, 200); } - @computed get dataDoc() { return this.props.document[DataSym]; } - @computed get fieldKey() { - const splits = StrCast(Doc.LayoutField(this.props.document)).split("fieldKey={\'"); - return splits.length > 1 ? splits[1].split("\'")[0] : "data"; - } + @computed get dataDoc() { return this.doc[DataSym]; } + @computed get layoutDoc() { return Doc.Layout(this.doc); } + @computed get fieldKey() { const splits = StrCast(Doc.LayoutField(this.doc)).split("fieldKey={\'"); return splits.length > 1 ? splits[1].split("\'")[0] : "data"; } childDocList(field: string) { - const layout = Doc.LayoutField(this.props.document) instanceof Doc ? Doc.LayoutField(this.props.document) as Doc : undefined; + const layout = Doc.LayoutField(this.doc) instanceof Doc ? Doc.LayoutField(this.doc) as Doc : undefined; return ((this.props.dataDoc ? DocListCast(this.props.dataDoc[field]) : undefined) || // if there's a data doc for an expanded template, use it's data field (layout ? Cast(layout[field], listSpec(Doc)) : undefined) || // else if there's a layout doc, display it's fields - Cast(this.props.document[field], listSpec(Doc))) as Doc[]; // otherwise use the document's data field + Cast(this.doc[field], listSpec(Doc))) as Doc[]; // otherwise use the document's data field } @computed get childDocs() { return this.childDocList(this.fieldKey); } @computed get childLinks() { return this.childDocList("links"); } @@ -109,22 +110,27 @@ class TreeView extends React.Component<TreeViewProps> { Doc.ComputeContentBounds(DocListCast(this.props.document[this.fieldKey])); } - @undoBatch openRight = () => this.props.addDocTab(this.props.document, "onRight", this.props.libraryPath); + @undoBatch openRight = () => this.props.addDocTab(this.doc, "onRight", this.props.libraryPath); @undoBatch move = (doc: Doc | Doc[], target: Doc | undefined, addDoc: (doc: Doc | Doc[]) => boolean) => { - return this.props.document !== target && this.props.deleteDoc(doc) && addDoc(doc); + return this.doc !== target && this.props.deleteDoc(doc) && addDoc(doc); } @undoBatch @action remove = (doc: Doc | Doc[], key: string) => { - return (doc instanceof Doc ? [doc] : doc).reduce((flg, doc) => - flg && Doc.RemoveDocFromList(this.dataDoc, key, doc), true); + return (doc instanceof Doc ? [doc] : doc).reduce((flg, doc) => flg && Doc.RemoveDocFromList(this.dataDoc, key, doc), true); } @undoBatch @action removeDoc = (doc: Doc | Doc[]) => { return (doc instanceof Doc ? [doc] : doc).reduce((flg, doc) => flg && Doc.RemoveDocFromList(this.props.containingCollection, Doc.LayoutFieldKey(this.props.containingCollection), doc), true); } + constructor(props: any) { + super(props); + this._editTitleScript = ScriptField.MakeScript(`{setInPlace(self, 'editTitle', '${this._uniqueId}'); selectDoc(self);} `); + if (Doc.GetT(this.doc, "editTitle", "string", true) === "*") Doc.SetInPlace(this.doc, "editTitle", this._uniqueId, false); + } + protected createTreeDropTarget = (ele: HTMLDivElement) => { this._treedropDisposer?.(); - ele && (this._treedropDisposer = DragManager.MakeDropTarget(ele, this.treeDrop.bind(this), undefined, this.preTreeDrop.bind(this)), this.props.document); + ele && (this._treedropDisposer = DragManager.MakeDropTarget(ele, this.treeDrop.bind(this), undefined, this.preTreeDrop.bind(this)), this.doc); } onPointerEnter = (e: React.PointerEvent): void => { @@ -136,7 +142,9 @@ class TreeView extends React.Component<TreeViewProps> { } onPointerLeave = (e: React.PointerEvent): void => { Doc.UnBrushDoc(this.dataDoc); - this._header!.current!.className = "treeViewItem-header"; + if (this._header?.current?.className !== "treeViewItem-header-editing") { + this._header!.current!.className = "treeViewItem-header"; + } document.removeEventListener("pointermove", this.onDragMove, true); } onDragMove = (e: PointerEvent): void => { @@ -144,7 +152,7 @@ class TreeView extends React.Component<TreeViewProps> { const pt = [e.clientX, e.clientY]; 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); + const inside = pt[0] > Math.min(rect.left + 75, rect.left + rect.width * .75) || (!before && this.treeViewOpen && this.childDocList.length); this._header!.current!.className = "treeViewItem-header"; if (inside) this._header!.current!.className += " treeViewItem-header-inside"; else if (before) this._header!.current!.className += " treeViewItem-header-above"; @@ -155,42 +163,38 @@ class TreeView extends React.Component<TreeViewProps> { editableView = (key: string, style?: string) => (<EditableView oneLine={true} display={"inline-block"} - editing={true /*this.dataDoc[Id] === EditableView.loadId*/} - contents={StrCast(this.props.document[key])} + editing={true} + contents={StrCast(this.doc[key])} height={12} + sizeToContent={true} fontStyle={style} fontSize={12} - GetValue={() => StrCast(this.props.document[key])} + GetValue={() => StrCast(this.doc[key])} SetValue={undoBatch((value: string) => { - Doc.SetInPlace(this.props.document, key, value, false) || true; - Doc.SetInPlace(this.props.document, "editTitle", undefined, false); + Doc.SetInPlace(this.doc, key, value, false) || true; + Doc.SetInPlace(this.doc, "editTitle", undefined, false); })} OnFillDown={undoBatch((value: string) => { - Doc.SetInPlace(this.props.document, key, value, false); - const doc = Docs.Create.FreeformDocument([], { title: "-", x: 0, y: 0, _width: 100, _height: 25, _LODdisable: true, templates: new List<string>([Templates.Title.Layout]) }); - Doc.SetInPlace(this.props.document, "editTitle", undefined, false); - Doc.SetInPlace(doc, "editTitle", true, false); + Doc.SetInPlace(this.doc, key, value, false); + const doc = Docs.Create.FreeformDocument([], { title: "-", x: 0, y: 0, _width: 100, _height: 25, templates: new List<string>([Templates.Title.Layout]) }); + Doc.SetInPlace(this.doc, "editTitle", undefined, false); + Doc.SetInPlace(doc, "editTitle", "*", false); return this.props.addDocument(doc); })} onClick={() => { SelectionManager.DeselectAll(); - Doc.UserDoc().activeSelection = new List([this.props.document]); + Doc.UserDoc().activeSelection = new List([this.doc]); return false; }} OnTab={undoBatch((shift?: boolean) => { - EditableView.loadId = this.dataDoc[Id]; shift ? this.props.outdentDocument?.() : this.props.indentDocument?.(); - setTimeout(() => { // unsetting/setting brushing for this doc will recreate & refocus this editableView after all other treeview changes have been made to the Dom (which may remove focus from this document). - Doc.UnBrushDoc(this.props.document); - Doc.BrushDoc(this.props.document); - EditableView.loadId = ""; - }, 0); + setTimeout(() => Doc.SetInPlace(this.doc, "editTitle", "*", false), 0); })} />) 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); + dragData && (dragData.dropAction = this.props.treeViewDoc === dragData.treeViewDoc ? "same" : dragData.dropAction); } @undoBatch @@ -198,18 +202,18 @@ class TreeView extends React.Component<TreeViewProps> { 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); + const inside = pt[0] > Math.min(rect.left + 75, rect.left + rect.width * .75) || (!before && this.treeViewOpen && this.childDocList.length); const complete = de.complete; if (complete.linkDragData) { const sourceDoc = complete.linkDragData.linkSourceDocument; - const destDoc = this.props.document; + const destDoc = this.doc; DocUtils.MakeLink({ doc: sourceDoc }, { doc: destDoc }, "tree link"); e.stopPropagation(); } const docDragData = complete.docDragData; if (docDragData) { e.stopPropagation(); - if (docDragData.draggedDocuments[0] === this.props.document) return true; + if (docDragData.draggedDocuments[0] === this.doc) return true; const parentAddDoc = (doc: Doc | Doc[]) => this.props.addDocument(doc, undefined, before); let addDoc = parentAddDoc; if (inside) { @@ -222,35 +226,28 @@ class TreeView extends React.Component<TreeViewProps> { return false; } - docTransform = () => { - const { scale, translateX, translateY } = Utils.GetScreenTransform(this._dref.current!); - const outerXf = this.props.outerXf(); - const offset = this.props.ScreenToLocalTransform().transformDirection((outerXf.translateX - translateX), outerXf.translateY - translateY); - const finalXf = this.props.ScreenToLocalTransform().translate(offset[0], offset[1]); - - return finalXf; - } - getTransform = () => { - const { scale, translateX, translateY } = Utils.GetScreenTransform(this._tref.current!); + refTransform = (ref: HTMLDivElement) => { + const { scale, translateX, translateY } = Utils.GetScreenTransform(ref); const outerXf = this.props.outerXf(); const offset = this.props.ScreenToLocalTransform().transformDirection(outerXf.translateX - translateX, outerXf.translateY - translateY); - const finalXf = this.props.ScreenToLocalTransform().translate(offset[0], offset[1]); - return finalXf; + return this.props.ScreenToLocalTransform().translate(offset[0], offset[1]); } + docTransform = () => this.refTransform(this._dref.current!); + getTransform = () => this.refTransform(this._tref.current!); docWidth = () => { - const layoutDoc = Doc.Layout(this.props.document); + const layoutDoc = this.layoutDoc; const aspect = NumCast(layoutDoc._nativeHeight, layoutDoc._fitWidth ? 0 : layoutDoc[HeightSym]()) / NumCast(layoutDoc._nativeWidth, layoutDoc._fitWidth ? 1 : layoutDoc[WidthSym]()); if (aspect) return Math.min(layoutDoc[WidthSym](), Math.min(this.MAX_EMBED_HEIGHT / aspect, this.props.panelWidth() - 20)); return NumCast(layoutDoc._nativeWidth) ? Math.min(layoutDoc[WidthSym](), this.props.panelWidth() - 20) : this.props.panelWidth() - 20; } docHeight = () => { - const layoutDoc = Doc.Layout(this.props.document); + const layoutDoc = this.layoutDoc; const bounds = this.boundsOfCollectionDocument; return Math.max(70, Math.min(this.MAX_EMBED_HEIGHT, (() => { const aspect = NumCast(layoutDoc._nativeHeight, layoutDoc._fitWidth ? 0 : layoutDoc[HeightSym]()) / NumCast(layoutDoc._nativeWidth, layoutDoc._fitWidth ? 1 : layoutDoc[WidthSym]()); if (aspect) return this.docWidth() * aspect; if (bounds) return this.docWidth() * (bounds.b - bounds.y) / (bounds.r - bounds.x); - return layoutDoc._fitWidth ? (!this.props.document._nativeHeight ? NumCast(this.props.containingCollection._height) : + return layoutDoc._fitWidth ? (!this.doc._nativeHeight ? NumCast(this.props.containingCollection._height) : Math.min(this.docWidth() * NumCast(layoutDoc.scrollHeight, NumCast(layoutDoc._nativeHeight)) / NumCast(layoutDoc._nativeWidth, NumCast(this.props.containingCollection._height)))) : NumCast(layoutDoc._height) ? NumCast(layoutDoc._height) : 50; @@ -259,7 +256,7 @@ class TreeView extends React.Component<TreeViewProps> { @computed get expandedField() { const ids: { [key: string]: string } = {}; - const doc = this.props.document; + const doc = this.doc; doc && Object.keys(doc).forEach(key => !(key in ids) && doc[key] !== ComputedField.undefined && (ids[key] = key)); const rows: JSX.Element[] = []; @@ -273,13 +270,12 @@ class TreeView extends React.Component<TreeViewProps> { const addDoc = (doc: Doc | Doc[], addBefore?: Doc, before?: boolean) => (doc instanceof Doc ? [doc] : doc).reduce( (flg, doc) => flg && Doc.AddDocToList(this.dataDoc, key, doc, addBefore, before, false, true), true); contentElement = TreeView.GetChildElements(contents instanceof Doc ? [contents] : - DocListCast(contents), this.props.treeViewId, doc, undefined, key, this.props.containingCollection, this.props.prevSibling, addDoc, remDoc, this.move, + DocListCast(contents), this.props.treeViewDoc, doc, undefined, key, this.props.containingCollection, this.props.prevSibling, addDoc, remDoc, this.move, this.props.dropAction, this.props.addDocTab, this.props.pinToPres, this.props.backgroundColor, this.props.ScreenToLocalTransform, this.props.outerXf, this.props.active, this.props.panelWidth, this.props.ChromeHeight, this.props.renderDepth, this.props.treeViewHideHeaderFields, this.props.treeViewPreventOpen, [...this.props.renderedIds, doc[Id]], this.props.libraryPath, this.props.onCheckedClick, this.props.onChildClick, this.props.ignoreFields); } else { - contentElement = <EditableView - key="editableView" + contentElement = <EditableView key="editableView" contents={contents !== undefined ? Field.toString(contents as Field) : "null"} height={13} fontSize={12} @@ -307,8 +303,8 @@ class TreeView extends React.Component<TreeViewProps> { return rows; } - rtfWidth = () => Math.min(Doc.Layout(this.props.document)?.[WidthSym](), this.props.panelWidth() - 20); - rtfHeight = () => this.rtfWidth() < Doc.Layout(this.props.document)?.[WidthSym]() ? Math.min(Doc.Layout(this.props.document)?.[HeightSym](), this.MAX_EMBED_HEIGHT) : this.MAX_EMBED_HEIGHT; + rtfWidth = () => Math.min(this.layoutDoc?.[WidthSym](), this.props.panelWidth() - 20); + rtfHeight = () => this.rtfWidth() <= this.layoutDoc?.[WidthSym]() ? Math.min(this.layoutDoc?.[HeightSym](), this.MAX_EMBED_HEIGHT) : this.MAX_EMBED_HEIGHT; @computed get renderContent() { TraceMobx(); @@ -320,32 +316,32 @@ class TreeView extends React.Component<TreeViewProps> { const docs = expandKey === "links" ? this.childLinks : this.childDocs; const sortKey = `${this.fieldKey}-sortAscending`; return <ul key={expandKey + "more"} onClick={(e) => { - this.props.document[sortKey] = (this.props.document[sortKey] ? false : (this.props.document[sortKey] === false ? undefined : true)); + this.doc[sortKey] = (this.doc[sortKey] ? false : (this.doc[sortKey] === false ? undefined : true)); e.stopPropagation(); }}> {!docs ? (null) : - TreeView.GetChildElements(docs, this.props.treeViewId, Doc.Layout(this.props.document), + TreeView.GetChildElements(docs, this.props.treeViewDoc, this.layoutDoc, this.dataDoc, expandKey, this.props.containingCollection, this.props.prevSibling, addDoc, remDoc, this.move, - StrCast(this.props.document.childDropAction, this.props.dropAction) as dropActionType, this.props.addDocTab, this.props.pinToPres, this.props.backgroundColor, this.props.ScreenToLocalTransform, + StrCast(this.doc.childDropAction, this.props.dropAction) as dropActionType, this.props.addDocTab, this.props.pinToPres, this.props.backgroundColor, this.props.ScreenToLocalTransform, this.props.outerXf, this.props.active, this.props.panelWidth, this.props.ChromeHeight, this.props.renderDepth, this.props.treeViewHideHeaderFields, this.props.treeViewPreventOpen, - [...this.props.renderedIds, this.props.document[Id]], this.props.libraryPath, this.props.onCheckedClick, this.props.onChildClick, this.props.ignoreFields)} + [...this.props.renderedIds, this.doc[Id]], this.props.libraryPath, this.props.onCheckedClick, this.props.onChildClick, this.props.ignoreFields)} </ul >; } else if (this.treeViewExpandedView === "fields") { - return <ul><div ref={this._dref} style={{ display: "inline-block" }} key={this.props.document[Id] + this.props.document.title}> + return <ul><div ref={this._dref} style={{ display: "inline-block" }} key={this.doc[Id] + this.doc.title}> {this.expandedField} </div></ul>; } else { - const layoutDoc = Doc.Layout(this.props.document); - const panelHeight = layoutDoc.type === DocumentType.RTF ? this.rtfHeight : this.docHeight; - const panelWidth = layoutDoc.type === DocumentType.RTF ? this.rtfWidth : this.docWidth; - return <div ref={this._dref} style={{ display: "inline-block", height: panelHeight() }} key={this.props.document[Id]}> + const layoutDoc = this.layoutDoc; + const panelHeight = StrCast(Doc.LayoutField(layoutDoc)).includes("FormattedTextBox") ? this.rtfHeight : this.docHeight; + const panelWidth = StrCast(Doc.LayoutField(layoutDoc)).includes("FormattedTextBox") ? this.rtfWidth : this.docWidth; + return <div ref={this._dref} style={{ display: "inline-block", height: panelHeight() }} key={this.doc[Id]}> <ContentFittingDocumentView Document={layoutDoc} DataDoc={this.dataDoc} LibraryPath={emptyPath} renderDepth={this.props.renderDepth + 1} rootSelected={returnTrue} - treeViewId={this.props.treeViewId[Id]} + treeViewDoc={undefined} backgroundColor={this.props.backgroundColor} fitToBox={this.boundsOfCollectionDocument !== undefined} FreezeDimensions={true} @@ -372,17 +368,17 @@ class TreeView extends React.Component<TreeViewProps> { } } - get onCheckedClick() { return this.props.onCheckedClick || ScriptCast(this.props.document.onCheckedClick); } + get onCheckedClick() { return this.props.onCheckedClick || ScriptCast(this.doc.onCheckedClick); } @action bulletClick = (e: React.MouseEvent) => { - if (this.onCheckedClick && this.props.document.type !== DocumentType.COL) { + if (this.onCheckedClick && this.doc.type !== DocumentType.COL) { // this.props.document.treeViewChecked = this.props.document.treeViewChecked === "check" ? "x" : this.props.document.treeViewChecked === "x" ? undefined : "check"; this.onCheckedClick.script.run({ - this: this.props.document.isTemplateForField && this.props.dataDoc ? this.props.dataDoc : this.props.document, + this: this.doc.isTemplateForField && this.props.dataDoc ? this.props.dataDoc : this.doc, heading: this.props.containingCollection.title, - checked: this.props.document.treeViewChecked === "check" ? "x" : this.props.document.treeViewChecked === "x" ? undefined : "check", - containingTreeView: this.props.treeViewId, + checked: this.doc.treeViewChecked === "check" ? "x" : this.doc.treeViewChecked === "x" ? undefined : "check", + containingTreeView: this.props.treeViewDoc, }, console.log); } else { this.treeViewOpen = !this.treeViewOpen; @@ -390,106 +386,112 @@ class TreeView extends React.Component<TreeViewProps> { e.stopPropagation(); } - @computed - get renderBullet() { - const checked = this.props.document.type === DocumentType.COL ? undefined : this.onCheckedClick ? (this.props.document.treeViewChecked ? this.props.document.treeViewChecked : "unchecked") : undefined; + @computed get renderBullet() { + TraceMobx(); + const checked = this.doc.type === DocumentType.COL ? undefined : this.onCheckedClick ? (this.doc.treeViewChecked ?? "unchecked") : undefined; return <div className="bullet" title={this.childDocs?.length ? `click to see ${this.childDocs?.length} items` : "view fields"} onClick={this.bulletClick} - style={{ color: StrCast(this.props.document.color, checked === "unchecked" ? "white" : "inherit"), opacity: checked === "unchecked" ? undefined : 0.4 }}> + style={{ color: StrCast(this.doc.color, checked === "unchecked" ? "white" : "inherit"), opacity: checked === "unchecked" ? undefined : 0.4 }}> {<FontAwesomeIcon icon={checked === "check" ? "check" : (checked === "x" ? "times" : checked === "unchecked" ? "square" : !this.treeViewOpen ? (this.childDocs ? "caret-square-right" : "caret-right") : (this.childDocs ? "caret-square-down" : "caret-down"))} />} </div>; } showContextMenu = (e: React.MouseEvent) => { this._docRef.current?.ContentDiv && simulateMouseClick(this._docRef.current.ContentDiv, e.clientX, e.clientY + 30, e.screenX, e.screenY + 30); - e.stopPropagation(); } focusOnDoc = (doc: Doc) => DocumentManager.Instance.getFirstDocumentView(doc)?.props.focus(doc, true); - contextMenuItems = () => { - const focusScript = ScriptField.MakeFunction(`DocFocus(self)`); - return [{ script: focusScript!, label: "Focus" }]; - } + contextMenuItems = () => [{ script: ScriptField.MakeFunction(`DocFocus(self)`)!, label: "Focus" }]; + truncateTitleWidth = () => NumCast(this.props.treeViewDoc.treeViewTruncateTitleWidth, 0); + showTitleEdit = () => ["*", this._uniqueId].includes(Doc.GetT(this.doc, "editTitle", "string", true) || ""); /** * Renders the EditableView title element for placement into the tree. */ @computed get renderTitle() { TraceMobx(); - (!TreeView._editTitleScript) && (TreeView._editTitleScript = ScriptField.MakeFunction("setInPlace(self, 'editTitle', true)")); - const headerElements = ( + const headerElements = this.props.treeViewHideHeaderFields() ? (null) : <> - <FontAwesomeIcon icon="cog" size="sm" onClick={e => this.showContextMenu(e)}></FontAwesomeIcon> + <FontAwesomeIcon icon="cog" size="sm" onClick={e => { this.showContextMenu(e); e.stopPropagation(); }} /> <span className="collectionTreeView-keyHeader" key={this.treeViewExpandedView} onPointerDown={action(() => { if (this.treeViewOpen) { - this.props.document.treeViewExpandedView = this.treeViewExpandedView === this.fieldKey ? (Doc.UserDoc().noviceMode ? "layout" : "fields") : - this.treeViewExpandedView === "fields" && Doc.Layout(this.props.document) ? "layout" : - this.treeViewExpandedView === "layout" && this.props.document.links ? "links" : + this.doc.treeViewExpandedView = this.treeViewExpandedView === this.fieldKey ? (Doc.UserDoc().noviceMode ? "layout" : "fields") : + this.treeViewExpandedView === "fields" && this.layoutDoc ? "layout" : + this.treeViewExpandedView === "layout" && DocListCast(this.doc.links).length ? "links" : this.childDocs ? this.fieldKey : (Doc.UserDoc().noviceMode ? "layout" : "fields"); } this.treeViewOpen = true; })}> {this.treeViewExpandedView} </span> - </>); - const openRight = (<div className="treeViewItem-openRight" onClick={this.openRight}> - <FontAwesomeIcon title="open in pane on right" icon="angle-right" size="lg" /> - </div>); + </>; + const view = this.showTitleEdit() ? this.editableView("title") : + <DocumentView + ref={this._docRef} + Document={this.doc} + DataDoc={undefined} + treeViewDoc={this.props.treeViewDoc} + LibraryPath={this.props.libraryPath || emptyPath} + addDocument={undefined} + addDocTab={this.props.addDocTab} + rootSelected={returnTrue} + pinToPres={emptyFunction} + onClick={this.props.onChildClick || this._editTitleScript} + dropAction={this.props.dropAction} + moveDocument={this.move} + removeDocument={this.removeDoc} + ScreenToLocalTransform={this.getTransform} + ContentScaling={returnOne} + PanelWidth={this.truncateTitleWidth} + PanelHeight={returnZero} + NativeHeight={returnZero} + NativeWidth={returnZero} + contextMenuItems={this.contextMenuItems} + renderDepth={1} + focus={returnTrue} + parentActive={returnTrue} + whenActiveChanged={emptyFunction} + bringToFront={emptyFunction} + dontRegisterView={BoolCast(this.props.treeViewDoc.dontRegisterChildViews)} + docFilters={returnEmptyFilter} + ContainingCollectionView={undefined} + ContainingCollectionDoc={this.props.containingCollection} + />; return <> <div className="docContainer" ref={this._tref} title="click to edit title" id={`docContainer-${this.props.parentKey}`} style={{ - fontWeight: this.props.document.searchMatch ? "bold" : undefined, - textDecoration: Doc.GetT(this.props.document, "title", "string", true) ? "underline" : undefined, - outline: BoolCast(this.props.document.workspaceBrush) ? "dashed 1px #06123232" : undefined, + fontWeight: this.doc.searchMatch ? "bold" : undefined, + textDecoration: Doc.GetT(this.doc, "title", "string", true) ? "underline" : undefined, + outline: BoolCast(this.doc.workspaceBrush) ? "dashed 1px #06123232" : undefined, pointerEvents: this.props.active() || SnappingManager.GetIsDragging() ? undefined : "none" }} > - {Doc.GetT(this.props.document, "editTitle", "boolean", true) ? - this.editableView("title") : - <DocumentView - ref={this._docRef} - Document={this.props.document} - DataDoc={undefined} - treeViewId={this.props.treeViewId[Id]} - LibraryPath={this.props.libraryPath || emptyPath} - addDocument={undefined} - addDocTab={this.props.addDocTab} - rootSelected={returnTrue} - pinToPres={emptyFunction} - onClick={this.props.onChildClick || TreeView._editTitleScript} - dropAction={this.props.dropAction} - moveDocument={this.move} - removeDocument={this.removeDoc} - ScreenToLocalTransform={this.getTransform} - ContentScaling={returnOne} - PanelWidth={returnZero} - PanelHeight={returnZero} - NativeHeight={returnZero} - NativeWidth={returnZero} - contextMenuItems={this.contextMenuItems} - renderDepth={1} - focus={returnTrue} - parentActive={returnTrue} - whenActiveChanged={emptyFunction} - bringToFront={emptyFunction} - dontRegisterView={BoolCast(this.props.treeViewId.dontRegisterChildViews)} - docFilters={returnEmptyFilter} - ContainingCollectionView={undefined} - ContainingCollectionDoc={this.props.containingCollection} - />} + {view} </div > - {this.props.treeViewHideHeaderFields() ? (null) : headerElements} - {openRight} + {headerElements} + <div className="treeViewItem-openRight" onClick={this.openRight}> + <FontAwesomeIcon title="open in pane on right" icon="external-link-alt" size="sm" /> + </div> </>; } render() { TraceMobx(); - const sorting = this.props.document[`${this.fieldKey}-sortAscending`]; - //setTimeout(() => runInAction(() => untracked(() => this._overrideTreeViewOpen = this.treeViewOpen)), 0); + const sorting = this.doc[`${this.fieldKey}-sortAscending`]; + if (this.showTitleEdit()) { // find containing CollectionTreeView and set our maximum width so the containing tree view won't have to scroll + let par: any = this._header?.current; + if (par) { + while (par && par.className !== "collectionTreeView-dropTarget") par = par.parentNode; + if (par) { + const par_rect = (par as HTMLElement).getBoundingClientRect(); + const my_recct = this._docRef.current?.ContentDiv?.getBoundingClientRect(); + this._editMaxWidth = Math.max(100, par_rect.right - (my_recct?.left || 0)); + } + } + } else this._editMaxWidth = ""; return <div className="treeViewItem-container" ref={this.createTreeDropTarget} onPointerDown={e => this.props.active() && SelectionManager.DeselectAll()}> <li className="collection-child"> - <div className="treeViewItem-header" ref={this._header} onClick={e => { + <div className={`treeViewItem-header` + (this._editMaxWidth ? "-editing" : "")} ref={this._header} style={{ maxWidth: this._editMaxWidth }} onClick={e => { if (this.props.active(true)) { e.stopPropagation(); e.preventDefault(); @@ -507,14 +509,14 @@ class TreeView extends React.Component<TreeViewProps> { {this.renderTitle} </div> <div className="treeViewItem-border" style={{ borderColor: sorting === undefined ? undefined : sorting ? "crimson" : "blue" }}> - {!this.treeViewOpen || this.props.renderedIds.indexOf(this.props.document[Id]) !== -1 ? (null) : this.renderContent} + {!this.treeViewOpen || this.props.renderedIds.indexOf(this.doc[Id]) !== -1 ? (null) : this.renderContent} </div> </li> </div>; } public static GetChildElements( childDocs: Doc[], - treeViewId: Doc, + treeViewDoc: Doc, containingCollection: Doc, dataDoc: Doc | undefined, key: string, @@ -624,7 +626,7 @@ class TreeView extends React.Component<TreeViewProps> { libraryPath={libraryPath ? [...libraryPath, containingCollection] : undefined} containingCollection={containingCollection} prevSibling={docs[i]} - treeViewId={treeViewId} + treeViewDoc={treeViewDoc} key={child[Id]} indentDocument={indent} outdentDocument={outdent} @@ -665,21 +667,22 @@ export class CollectionTreeView extends CollectionSubView<Document, Partial<coll private treedropDisposer?: DragManager.DragDropDisposer; private _mainEle?: HTMLDivElement; - @computed get dataDoc() { return this.props.DataDoc || this.props.Document; } + @computed get doc() { return this.props.Document; } + @computed get dataDoc() { return this.props.DataDoc || this.doc; } protected createTreeDropTarget = (ele: HTMLDivElement) => { this.treedropDisposer?.(); if (this._mainEle = ele) { - this.treedropDisposer = DragManager.MakeDropTarget(ele, this.onInternalDrop.bind(this), this.props.Document, this.onInternalPreDrop.bind(this)); + this.treedropDisposer = DragManager.MakeDropTarget(ele, this.onInternalDrop.bind(this), this.doc, 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))) { + if (targetAction && !dragData.draggedDocuments.some(d => d.context === this.doc && this.childDocs.includes(d))) { dragData.dropAction = targetAction; - } else dragData.dropAction = this.props.Document[Id] === dragData?.treeViewId ? "same" : dragData.dropAction; + } else dragData.dropAction = this.doc === dragData?.treeViewDoc ? "same" : dragData.dropAction; } } @@ -691,7 +694,7 @@ export class CollectionTreeView extends CollectionSubView<Document, Partial<coll @action remove = (doc: Doc | Doc[]): boolean => { const docs = doc instanceof Doc ? [doc] : doc; - const targetDataDoc = this.props.Document[DataSym]; + const targetDataDoc = this.doc[DataSym]; const value = DocListCast(targetDataDoc[this.props.fieldKey]); const result = value.filter(v => !docs.includes(v)); if (result.length !== value.length) { @@ -704,9 +707,9 @@ export class CollectionTreeView extends CollectionSubView<Document, Partial<coll addDoc = (doc: Doc | Doc[], relativeTo: Opt<Doc>, before?: boolean): boolean => { const doAddDoc = (doc: Doc | Doc[]) => (doc instanceof Doc ? [doc] : doc).reduce((flg, doc) => - flg && Doc.AddDocToList(this.props.Document[DataSym], this.props.fieldKey, doc, relativeTo, before, false, false, false), true); - if (this.props.Document.resolvedDataDoc instanceof Promise) { - this.props.Document.resolvedDataDoc.then((resolved: any) => doAddDoc(doc)); + flg && Doc.AddDocToList(this.doc[DataSym], this.props.fieldKey, doc, relativeTo, before, false, false, false), true); + if (this.doc.resolvedDataDoc instanceof Promise) { + this.doc.resolvedDataDoc.then((resolved: any) => doAddDoc(doc)); } else { doAddDoc(doc); } @@ -714,22 +717,23 @@ export class CollectionTreeView extends CollectionSubView<Document, Partial<coll } onContextMenu = (e: React.MouseEvent): void => { // need to test if propagation has stopped because GoldenLayout forces a parallel react hierarchy to be created for its top-level layout - if (!e.isPropagationStopped() && this.props.Document === Doc.UserDoc().myWorkspaces) { + if (!e.isPropagationStopped() && this.doc === Doc.UserDoc().myWorkspaces) { ContextMenu.Instance.addItem({ description: "Create Workspace", event: () => MainView.Instance.createNewWorkspace(), icon: "plus" }); - ContextMenu.Instance.addItem({ description: "Delete Workspace", event: () => this.remove(this.props.Document), icon: "minus" }); + ContextMenu.Instance.addItem({ description: "Delete Workspace", event: () => this.remove(this.doc), icon: "minus" }); e.stopPropagation(); e.preventDefault(); ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15); - } else if (!e.isPropagationStopped() && this.props.Document === Doc.UserDoc().myRecentlyClosed) { + } else if (!e.isPropagationStopped() && this.doc === Doc.UserDoc().myRecentlyClosed) { ContextMenu.Instance.addItem({ description: "Clear All", event: () => Doc.UserDoc().myRecentlyClosed = new List<Doc>(), icon: "plus" }); e.stopPropagation(); e.preventDefault(); ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15); } else { const layoutItems: ContextMenuProps[] = []; - layoutItems.push({ description: (this.props.Document.treeViewPreventOpen ? "Persist" : "Abandon") + "Treeview State", event: () => this.props.Document.treeViewPreventOpen = !this.props.Document.treeViewPreventOpen, icon: "paint-brush" }); - layoutItems.push({ description: (this.props.Document.treeViewHideHeaderFields ? "Show" : "Hide") + " Header Fields", event: () => this.props.Document.treeViewHideHeaderFields = !this.props.Document.treeViewHideHeaderFields, icon: "paint-brush" }); - layoutItems.push({ description: (this.props.Document.treeViewHideTitle ? "Show" : "Hide") + " Title", event: () => this.props.Document.treeViewHideTitle = !this.props.Document.treeViewHideTitle, icon: "paint-brush" }); + layoutItems.push({ description: (this.doc.treeViewPreventOpen ? "Persist" : "Abandon") + "Treeview State", event: () => this.doc.treeViewPreventOpen = !this.doc.treeViewPreventOpen, icon: "paint-brush" }); + layoutItems.push({ description: (this.doc.treeViewHideHeaderFields ? "Show" : "Hide") + " Header Fields", event: () => this.doc.treeViewHideHeaderFields = !this.doc.treeViewHideHeaderFields, icon: "paint-brush" }); + layoutItems.push({ description: (this.doc.treeViewHideTitle ? "Show" : "Hide") + " Title", event: () => this.doc.treeViewHideTitle = !this.doc.treeViewHideTitle, icon: "paint-brush" }); + layoutItems.push({ description: (this.doc.treeViewHideLinkLines ? "Show" : "Hide") + " Link Lines", event: () => this.doc.treeViewHideLinkLines = !this.doc.treeViewHideLinkLines, icon: "paint-brush" }); ContextMenu.Instance.addItem({ description: "Options...", subitems: layoutItems, icon: "eye" }); } !Doc.UserDoc().noviceMode && ContextMenu.Instance.addItem({ @@ -745,7 +749,7 @@ export class CollectionTreeView extends CollectionSubView<Document, Partial<coll const fallback = ImageDocument("http://cs.brown.edu/~bcz/face.gif", { _width: 400 }); // replace with desired double click target let pdfContent: string; - DocListCast(this.dataDoc[this.props.fieldKey]).map(d => { + this.childDocs?.map(d => { DocListCast(d.data).map((img, i) => { const caption = (d.captions as any)[i]; if (caption) { @@ -774,7 +778,7 @@ export class CollectionTreeView extends CollectionSubView<Document, Partial<coll const existingOnClick = ContextMenu.Instance.findByDescription("OnClick..."); const onClicks: ContextMenuProps[] = existingOnClick && "subitems" in existingOnClick ? existingOnClick.subitems : []; onClicks.push({ - description: "Edit onChecked Script", event: () => UndoManager.RunInBatch(() => DocUtils.makeCustomViewClicked(this.props.Document, undefined, "onCheckedClick"), "edit onCheckedClick"), icon: "edit" + description: "Edit onChecked Script", event: () => UndoManager.RunInBatch(() => DocUtils.makeCustomViewClicked(this.doc, undefined, "onCheckedClick"), "edit onCheckedClick"), icon: "edit" }); !existingOnClick && ContextMenu.Instance.addItem({ description: "OnClick...", subitems: onClicks, icon: "hand-point-right" }); } @@ -784,7 +788,7 @@ export class CollectionTreeView extends CollectionSubView<Document, Partial<coll @computed get renderClearButton() { return <div id="toolbar" key="toolbar"> <button className="toolbar-button round-button" title="Empty" - onClick={undoBatch(action(() => Doc.GetProto(this.props.Document)[this.props.fieldKey] = undefined))}> + onClick={undoBatch(action(() => Doc.GetProto(this.doc)[this.props.fieldKey] = undefined))}> <FontAwesomeIcon icon={"trash"} size="sm" /> </button> </div >; @@ -795,51 +799,51 @@ export class CollectionTreeView extends CollectionSubView<Document, Partial<coll } render() { TraceMobx(); - if (!(this.props.Document instanceof Doc)) return (null); - const dropAction = StrCast(this.props.Document.childDropAction) as dropActionType; + if (!(this.doc instanceof Doc)) return (null); + const dropAction = StrCast(this.doc.childDropAction) as dropActionType; const addDoc = (doc: Doc | Doc[], relativeTo?: Doc, before?: boolean) => this.addDoc(doc, relativeTo, before); const moveDoc = (d: Doc | Doc[], target: Doc | undefined, addDoc: (doc: Doc | Doc[]) => boolean) => this.props.moveDocument(d, target, addDoc); const childDocs = this.props.overrideDocuments ? this.props.overrideDocuments : this.childDocs; return !childDocs ? (null) : ( - <div className="collectionTreeView-dropTarget" id="body" - style={{ - 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`, - pointerEvents: !this.props.active() && !SnappingManager.GetIsDragging() ? "none" : undefined - }} - onKeyPress={this.onKeyPress} - onContextMenu={this.onContextMenu} - onWheel={(e: React.WheelEvent) => this._mainEle && this._mainEle.scrollHeight > this._mainEle.clientHeight && e.stopPropagation()} - onDrop={this.onTreeDrop} - ref={this.createTreeDropTarget}> - {(this.props.treeViewHideTitle || this.props.Document.treeViewHideTitle ? (null) : <EditableView - contents={this.dataDoc.title} - editing={false} - display={"block"} - maxHeight={72} - height={"auto"} - GetValue={() => StrCast(this.dataDoc.title)} - SetValue={undoBatch((value: string) => Doc.SetInPlace(this.dataDoc, "title", value, false) || true)} - OnFillDown={undoBatch((value: string) => { - Doc.SetInPlace(this.dataDoc, "title", value, false); - const doc = Docs.Create.FreeformDocument([], { title: "", x: 0, y: 0, _width: 100, _height: 25, _LODdisable: true, templates: new List<string>([Templates.Title.Layout]) }); - EditableView.loadId = doc[Id]; - Doc.SetInPlace(doc, "editTitle", true, false); - this.addDoc(doc, childDocs.length ? childDocs[0] : undefined, true); - })} />)} - {this.props.Document.allowClear ? this.renderClearButton : (null)} - <ul className="no-indent" style={{ width: "max-content" }} > - { - TreeView.GetChildElements(childDocs, this.props.Document, this.props.Document, this.props.DataDoc, this.props.fieldKey, this.props.ContainingCollectionDoc, undefined, addDoc, this.remove, - moveDoc, dropAction, this.props.addDocTab, this.props.pinToPres, this.props.backgroundColor, this.props.ScreenToLocalTransform, - this.outerXf, this.props.active, this.props.PanelWidth, this.props.ChromeHeight, this.props.renderDepth, () => this.props.treeViewHideHeaderFields || BoolCast(this.props.Document.treeViewHideHeaderFields), - BoolCast(this.props.Document.treeViewPreventOpen), [], this.props.LibraryPath, this.props.onCheckedClick, - this.props.onChildClick || ScriptCast(this.props.Document.onChildClick), this.props.ignoreFields) - } - </ul> - </div > + <div className="collectionTreeView-container" onContextMenu={this.onContextMenu}> + <div className="collectionTreeView-dropTarget" id="body" + style={{ + background: this.props.backgroundColor?.(this.doc), + paddingLeft: `${NumCast(this.doc._xPadding, 10)}px`, + paddingRight: `${NumCast(this.doc._xPadding, 10)}px`, + paddingTop: `${NumCast(this.doc._yPadding, 20)}px`, + pointerEvents: !this.props.active() && !SnappingManager.GetIsDragging() ? "none" : undefined + }} + onKeyPress={this.onKeyPress} + onWheel={(e) => this._mainEle && this._mainEle.scrollHeight > this._mainEle.clientHeight && e.stopPropagation()} + onDrop={this.onTreeDrop} + ref={this.createTreeDropTarget}> + {this.props.treeViewHideTitle || this.doc.treeViewHideTitle ? (null) : <EditableView + contents={this.dataDoc.title} + editing={false} + display={"block"} + maxHeight={72} + height={"auto"} + GetValue={() => StrCast(this.dataDoc.title)} + SetValue={undoBatch((value: string) => Doc.SetInPlace(this.dataDoc, "title", value, false) || true)} + OnFillDown={undoBatch((value: string) => { + Doc.SetInPlace(this.dataDoc, "title", value, false); + const doc = Docs.Create.FreeformDocument([], { title: "", x: 0, y: 0, _width: 100, _height: 25, templates: new List<string>([Templates.Title.Layout]) }); + Doc.SetInPlace(doc, "editTitle", "*", false); + this.addDoc(doc, childDocs.length ? childDocs[0] : undefined, true); + })} />} + {this.doc.allowClear ? this.renderClearButton : (null)} + <ul className="no-indent" style={{ width: "max-content" }} > + { + TreeView.GetChildElements(childDocs, this.doc, this.doc, this.props.DataDoc, this.props.fieldKey, this.props.ContainingCollectionDoc, undefined, addDoc, this.remove, + moveDoc, dropAction, this.props.addDocTab, this.props.pinToPres, this.props.backgroundColor, this.props.ScreenToLocalTransform, + this.outerXf, this.props.active, this.props.PanelWidth, this.props.ChromeHeight, this.props.renderDepth, () => this.props.treeViewHideHeaderFields || BoolCast(this.doc.treeViewHideHeaderFields), + BoolCast(this.doc.treeViewPreventOpen), [], this.props.LibraryPath, this.props.onCheckedClick, + this.props.onChildClick || ScriptCast(this.doc.onChildClick), this.props.ignoreFields) + } + </ul> + </div > + </div> ); } } diff --git a/src/client/views/collections/CollectionView.scss b/src/client/views/collections/CollectionView.scss index 7877fe155..b630f9cf8 100644 --- a/src/client/views/collections/CollectionView.scss +++ b/src/client/views/collections/CollectionView.scss @@ -11,16 +11,18 @@ height: 100%; overflow: hidden; // bcz: used to be 'auto' which would create scrollbars when there's a floating doc that's not visible. not sure if that's better, but the scrollbars are annoying... - .collectionTimeView-dragger { - background-color: lightgray; + .collectionView-filterDragger { + background-color: rgb(140, 139, 139); height: 40px; - width: 20px; + width: 10px; position: absolute; - border-radius: 10px; top: 55%; border: 1px black solid; + border-radius: 0; + border-top-left-radius: 20px; + border-bottom-left-radius: 20px; + border-right: unset; z-index: 2; - right: -10px; } .collectionTimeView-treeView { display: flex; @@ -30,6 +32,8 @@ position: absolute; right: 0; top: 0; + border-left: solid 1px; + z-index: 1; .collectionTimeView-addfacet { display: inline-block; diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index 508b9e5e7..26abd2529 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -12,25 +12,29 @@ import { AclAddonly, AclReadonly, AclSym, DataSym, Doc, DocListCast, Field, Opt import { Id } from '../../../fields/FieldSymbols'; import { List } from '../../../fields/List'; import { ObjectField } from '../../../fields/ObjectField'; +import { RichTextField } from '../../../fields/RichTextField'; import { listSpec } from '../../../fields/Schema'; import { ComputedField, ScriptField } from '../../../fields/ScriptField'; import { BoolCast, Cast, NumCast, ScriptCast, StrCast } from '../../../fields/Types'; import { ImageField } from '../../../fields/URLField'; import { TraceMobx } from '../../../fields/util'; -import { emptyFunction, emptyPath, returnFalse, returnOne, returnZero, setupMoveUpEvents, Utils, returnEmptyFilter } from '../../../Utils'; -import { Docs } from '../../documents/Documents'; +import { emptyFunction, emptyPath, returnEmptyFilter, returnFalse, returnOne, returnZero, setupMoveUpEvents, Utils } from '../../../Utils'; +import { Docs, DocUtils } from '../../documents/Documents'; import { DocumentType } from '../../documents/DocumentTypes'; import { CurrentUserUtils } from '../../util/CurrentUserUtils'; import { ImageUtils } from '../../util/Import & Export/ImageUtils'; import { InteractionUtils } from '../../util/InteractionUtils'; +import { UndoManager } from '../../util/UndoManager'; import { ContextMenu } from "../ContextMenu"; import { FieldView, FieldViewProps } from '../nodes/FieldView'; import { ScriptBox } from '../ScriptBox'; import { Touchable } from '../Touchable'; +import { CollectionCarousel3DView } from './CollectionCarousel3DView'; import { CollectionCarouselView } from './CollectionCarouselView'; import { CollectionDockingView } from "./CollectionDockingView"; import { AddCustomFreeFormLayout } from './collectionFreeForm/CollectionFreeFormLayoutEngines'; import { CollectionFreeFormView } from './collectionFreeForm/CollectionFreeFormView'; +import { CollectionGridView } from './collectionGrid/CollectionGridView'; import { CollectionLinearView } from './CollectionLinearView'; import CollectionMapView from './CollectionMapView'; import { CollectionMulticolumnView } from './collectionMulticolumn/CollectionMulticolumnView'; @@ -42,10 +46,8 @@ 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'; -import { UndoManager } from '../../util/UndoManager'; const higflyout = require("@hig/flyout"); export const { anchorPoints } = higflyout; export const Flyout = higflyout.default; @@ -66,6 +68,7 @@ export enum CollectionViewType { Multirow = "multirow", Time = "time", Carousel = "carousel", + Carousel3D = "3D Carousel", Linear = "linear", Staff = "staff", Map = "map", @@ -106,7 +109,7 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus get collectionViewType(): CollectionViewType | undefined { const viewField = StrCast(this.props.Document._viewType); if (CollectionView._safeMode) { - if (viewField === CollectionViewType.Freeform) { + if (viewField === CollectionViewType.Freeform || viewField === CollectionViewType.Schema) { return CollectionViewType.Tree; } if (viewField === CollectionViewType.Invalid) { @@ -135,7 +138,23 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus } else if (this.dataDoc[AclSym] === AclAddonly) { added.map(doc => Doc.AddDocToList(targetDataDoc, this.props.fieldKey, doc)); } else { - added.map(doc => doc.context = this.props.Document); + added.map(doc => { + const context = Cast(doc.context, Doc, null); + if (context && (context.type === DocumentType.VID || context.type === DocumentType.WEB || context.type === DocumentType.PDF || context.type === DocumentType.IMG) && + !DocListCast(doc.links).some(d => d.isPushpin)) { + const pushpin = Docs.Create.FontIconDocument({ + icon: "map-pin", x: Cast(doc.x, "number", null), y: Cast(doc.y, "number", null), _backgroundColor: "#0000003d", color: "#ACCEF7", + _width: 15, _height: 15, _xPadding: 0, isLinkButton: true, displayTimecode: Cast(doc.displayTimecode, "number", null) + }); + Doc.AddDocToList(context, Doc.LayoutFieldKey(context) + "-annotations", pushpin); + const pushpinLink = DocUtils.MakeLink({ doc: pushpin }, { doc: doc }, "pushpin"); + const first = DocListCast(pushpin.links).find(d => d instanceof Doc); + first && (first.hidden = true); + pushpinLink && (Doc.GetProto(pushpinLink).isPushpin = true); + doc.displayTimecode = undefined; + } + doc.context = this.props.Document; + }); added.map(add => Doc.AddDocToList(Cast(Doc.UserDoc().myCatalog, Doc, null), "data", add)); targetDataDoc[this.props.fieldKey] = new List<Doc>([...docList, ...added]); targetDataDoc[this.props.fieldKey + "-lastModified"] = new DateField(new Date(Date.now())); @@ -160,7 +179,7 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus // this is called with the document that was dragged and the collection to move it into. // if the target collection is the same as this collection, then the move will be allowed. // otherwise, the document being moved must be able to be removed from its container before - // moving it into the target. + // moving it into the target. @action.bound moveDocument = (doc: Doc | Doc[], targetCollection: Doc | undefined, addDocument: (doc: Doc | Doc[]) => boolean): boolean => { if (Doc.AreProtosEqual(this.props.Document, targetCollection)) { @@ -182,7 +201,7 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus showIsTagged = () => { return (null); - // this section would display an icon in the bototm right of a collection to indicate that all + // this section would display an icon in the bototm right of a collection to indicate that all // photos had been processed through Google's content analysis API and Google's tags had been // assigned to the documents googlePhotosTags field. // const children = DocListCast(this.props.Document[this.props.fieldKey]); @@ -191,7 +210,7 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus // return !allTagged ? (null) : <img id={"google-tags"} src={"/assets/google_tags.png"} />; } - screenToLocalTransform = () => this.props.ScreenToLocalTransform().scale(this.props.PanelWidth() / this.bodyPanelWidth()); + screenToLocalTransform = () => this.props.renderDepth ? this.props.ScreenToLocalTransform() : this.props.ScreenToLocalTransform().scale(this.props.PanelWidth() / this.bodyPanelWidth()); private SubViewHelper = (type: CollectionViewType, renderProps: CollectionRenderProps) => { const props: SubCollectionViewProps = { ...this.props, ...renderProps, ScreenToLocalTransform: this.screenToLocalTransform, CollectionView: this, annotationsKey: "" }; switch (type) { @@ -204,8 +223,9 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus case CollectionViewType.Linear: { return (<CollectionLinearView key="collview" {...props} />); } case CollectionViewType.Pile: { return (<CollectionPileView key="collview" {...props} />); } case CollectionViewType.Carousel: { return (<CollectionCarouselView key="collview" {...props} />); } - case CollectionViewType.Stacking: { this.props.Document.singleColumn = true; return (<CollectionStackingView key="collview" {...props} />); } - case CollectionViewType.Masonry: { this.props.Document.singleColumn = false; return (<CollectionStackingView key="collview" {...props} />); } + case CollectionViewType.Carousel3D: { return (<CollectionCarousel3DView key="collview" {...props} />); } + case CollectionViewType.Stacking: { this.props.Document._columnsStack = true; return (<CollectionStackingView key="collview" {...props} />); } + case CollectionViewType.Masonry: { this.props.Document._columnsStack = 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} />); @@ -244,6 +264,7 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus subItems.push({ description: "Multirow", event: () => func(CollectionViewType.Multirow), icon: "columns" }); subItems.push({ description: "Masonry", event: () => func(CollectionViewType.Masonry), icon: "columns" }); subItems.push({ description: "Carousel", event: () => func(CollectionViewType.Carousel), icon: "columns" }); + subItems.push({ description: "3D Carousel", event: () => func(CollectionViewType.Carousel3D), 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" }); @@ -255,7 +276,8 @@ 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 + const cm = ContextMenu.Instance; + if (cm && !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; @@ -263,7 +285,7 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus return newRendition; }, false); - const existing = ContextMenu.Instance.findByDescription("Options..."); + const existing = cm.findByDescription("Options..."); const layoutItems = existing && "subitems" in existing ? existing.subitems : []; layoutItems.push({ description: `${this.props.Document.forceActive ? "Select" : "Force"} Contents Active`, event: () => this.props.Document.forceActive = !this.props.Document.forceActive, icon: "project-diagram" }); if (this.props.Document.childLayout instanceof Doc) { @@ -274,9 +296,9 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus } layoutItems.push({ description: `${this.props.Document.isInPlaceContainer ? "Unset" : "Set"} inPlace Container`, event: () => this.props.Document.isInPlaceContainer = !this.props.Document.isInPlaceContainer, icon: "project-diagram" }); - !existing && ContextMenu.Instance.addItem({ description: "Options...", subitems: layoutItems, icon: "hand-point-right" }); + !existing && cm.addItem({ description: "Options...", subitems: layoutItems, icon: "hand-point-right" }); - const existingOnClick = ContextMenu.Instance.findByDescription("OnClick..."); + const existingOnClick = cm.findByDescription("OnClick..."); const onClicks = existingOnClick && "subitems" in existingOnClick ? existingOnClick.subitems : []; const funcs = [ { key: "onChildClick", name: "On Child Clicked" }, @@ -292,13 +314,13 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus icon: "edit", event: () => this.props.Document[StrCast(childClick.targetScriptKey)] = ObjectField.MakeCopy(ScriptCast(childClick.data)), })); - !existingOnClick && ContextMenu.Instance.addItem({ description: "OnClick...", subitems: onClicks, icon: "hand-point-right" }); + !existingOnClick && cm.addItem({ description: "OnClick...", subitems: onClicks, icon: "hand-point-right" }); if (!Doc.UserDoc().noviceMode) { - const more = ContextMenu.Instance.findByDescription("More..."); + const more = cm.findByDescription("More..."); const moreItems = more && "subitems" in more ? more.subitems : []; moreItems.push({ description: "Export Image Hierarchy", icon: "columns", event: () => ImageUtils.ExportHierarchyToFileSystem(this.props.Document) }); - !more && ContextMenu.Instance.addItem({ description: "More...", subitems: moreItems, icon: "hand-point-right" }); + !more && cm.addItem({ description: "More...", subitems: moreItems, icon: "hand-point-right" }); } } } @@ -353,10 +375,11 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus return viewSpecScript ? docs.filter(d => viewSpecScript.script.run({ doc: d }, console.log).result) : docs; } @computed get _allFacets() { - const facets = new Set<string>(); - this.childDocs.filter(child => child).forEach(child => Object.keys(Doc.GetProto(child)).forEach(key => facets.add(key))); + TraceMobx(); + const facets = new Set<string>(["type", "text", "data", "author", "ACL"]); + this.childDocs.filter(child => child).forEach(child => child && Object.keys(Doc.GetProto(child)).forEach(key => facets.add(key))); Doc.AreProtosEqual(this.dataDoc, this.props.Document) && this.childDocs.filter(child => child).forEach(child => Object.keys(child).forEach(key => facets.add(key))); - return Array.from(facets); + return Array.from(facets).filter(f => !f.startsWith("_") && !["proto", "zIndex", "isPrototype", "context", "text-noTemplate"].includes(f)).sort(); } /** @@ -383,8 +406,13 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus } } else { const allCollectionDocs = DocListCast(this.dataDoc[this.props.fieldKey]); - const facetValues = Array.from(allCollectionDocs.reduce((set, child) => - set.add(Field.toString(child[facetHeader] as Field)), new Set<string>())); + var rtfields = 0; + const facetValues = Array.from(allCollectionDocs.reduce((set, child) => { + const field = child[facetHeader] as Field; + const fieldStr = Field.toString(field); + if (field instanceof RichTextField || (typeof (field) === "string" && fieldStr.split(" ").length > 2)) rtfields++; + return set.add(fieldStr); + }, new Set<string>())); let nonNumbers = 0; let minVal = Number.MAX_VALUE, maxVal = -Number.MAX_VALUE; @@ -398,13 +426,18 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus } }); let newFacet: Opt<Doc>; - if (nonNumbers / allCollectionDocs.length < .1) { - newFacet = Docs.Create.SliderDocument({ title: facetHeader }); + if (facetHeader === "text" || rtfields / allCollectionDocs.length > 0.1) { + newFacet = Docs.Create.TextDocument("", { _width: 100, _height: 25, treeViewExpandedView: "layout", title: facetHeader, treeViewOpen: true, forceActive: true, ignoreClick: true }); + Doc.GetProto(newFacet).type = DocumentType.COL; // forces item to show an open/close button instead ofa checkbox + newFacet.target = this.props.Document; + newFacet._textBoxPadding = 4; + const scriptText = `setDocFilter(this.target, "${facetHeader}", text, "match")`; + newFacet.onTextChanged = ScriptField.MakeScript(scriptText, { this: Doc.name, text: "string" }); + } else if (nonNumbers / facetValues.length < .1) { + newFacet = Docs.Create.SliderDocument({ title: facetHeader, treeViewExpandedView: "layout", treeViewOpen: true }); const newFacetField = Doc.LayoutFieldKey(newFacet); const ranged = Doc.readDocRangeFilter(this.props.Document, facetHeader); Doc.GetProto(newFacet).type = DocumentType.COL; // forces item to show an open/close button instead ofa checkbox - newFacet.treeViewExpandedView = "layout"; - newFacet.treeViewOpen = true; const extendedMinVal = minVal - Math.min(1, Math.abs(maxVal - minVal) * .05); const extendedMaxVal = maxVal + Math.min(1, Math.abs(maxVal - minVal) * .05); newFacet[newFacetField + "-min"] = ranged === undefined ? extendedMinVal : ranged[0]; @@ -414,7 +447,6 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus newFacet.target = this.props.Document; const scriptText = `setDocFilterRange(this.target, "${facetHeader}", range)`; newFacet.onThumbChanged = ScriptField.MakeScript(scriptText, { this: Doc.name, range: "number" }); - Doc.AddDocToList(facetCollection, this.props.fieldKey + "-filter", newFacet); } else { newFacet = new Doc(); @@ -432,7 +464,7 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus setupMoveUpEvents(this, e, action((e: PointerEvent, down: number[], delta: number[]) => { this._facetWidth = this.props.PanelWidth() - Math.max(this.props.ScreenToLocalTransform().transformPoint(e.clientX, 0)[0], 0); return false; - }), returnFalse, action(() => this._facetWidth = this.facetWidth() < 15 ? Math.min(this.props.PanelWidth() - 25, 200) : 0)); + }), returnFalse, action(() => this._facetWidth = this.facetWidth() < 15 ? Math.min(this.props.PanelWidth() - 25, 200) : 0), false); } filterBackground = () => "rgba(105, 105, 105, 0.432)"; get ignoreFields() { return ["_docFilters", "_docRangeFilters"]; } // this makes the tree view collection ignore these filters (otherwise, the filters would filter themselves) @@ -441,6 +473,7 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus return ScriptField.MakeScript(scriptText, { this: Doc.name, heading: "string", checked: "string", containingTreeView: Doc.name }); } @computed get filterView() { + TraceMobx(); const facetCollection = this.props.Document; const flyout = ( <div className="collectionTimeView-flyout" style={{ width: `${this.facetWidth()}`, height: this.props.PanelHeight() - 30 }} onWheel={e => e.stopPropagation()}> @@ -530,12 +563,11 @@ export class CollectionView extends Touchable<FieldViewProps & CollectionViewCus Utils.CorsProxy(Cast(d.data, ImageField)!.url.href) : Cast(d.data, ImageField)!.url.href : ""))} - {!this.props.isSelected() || this.props.PanelHeight() < 100 || this.props.Document.hideFilterView ? (null) : - <div className="collectionTimeView-dragger" title="library View Dragger" onPointerDown={this.onPointerDown} style={{ right: this.facetWidth() - 10 }} /> + {(!this.props.isSelected() || this.props.Document.hideFilterView) && !this.props.Document.forceActive ? (null) : + <div className="collectionView-filterDragger" title="library View Dragger" onPointerDown={this.onPointerDown} + style={{ right: this.facetWidth() - 1, top: this.props.Document._viewType === CollectionViewType.Docking ? "25%" : "55%" }} /> } {this.facetWidth() < 10 ? (null) : this.filterView} </div>); } } - - diff --git a/src/client/views/collections/CollectionViewChromes.scss b/src/client/views/collections/CollectionViewChromes.scss index 77a12ed37..b1e8d20ad 100644 --- a/src/client/views/collections/CollectionViewChromes.scss +++ b/src/client/views/collections/CollectionViewChromes.scss @@ -16,6 +16,7 @@ height: 32px; border-bottom: .5px solid rgb(180, 180, 180); overflow: visible; + z-index: 9001; .collectionViewBaseChrome { display: flex; @@ -80,6 +81,12 @@ // margin-top: 10px; } + @media only screen and (max-device-width: 480px) { + .collectionViewBaseChrome-collapse { + display: none; + } + } + .collectionViewBaseChrome-template, .collectionViewBaseChrome-viewModes { display: grid; @@ -169,7 +176,8 @@ } .collectionStackingViewChrome-cont, - .collectionTreeViewChrome-cont { + .collectionTreeViewChrome-cont, + .collection3DCarouselViewChrome-cont { display: flex; justify-content: space-between; } @@ -234,21 +242,24 @@ .collectionStackingViewChrome-pivotField-cont, - .collectionTreeViewChrome-pivotField-cont { + .collectionTreeViewChrome-pivotField-cont, + .collection3DCarouselViewChrome-scrollSpeed-cont { justify-self: right; display: flex; font-size: 75%; letter-spacing: 2px; .collectionStackingViewChrome-pivotField-label, - .collectionTreeViewChrome-pivotField-label { + .collectionTreeViewChrome-pivotField-label, + .collection3DCarouselViewChrome-scrollSpeed-label { vertical-align: center; padding-left: 10px; margin: auto; } .collectionStackingViewChrome-pivotField, - .collectionTreeViewChrome-pivotField { + .collectionTreeViewChrome-pivotField, + .collection3DCarouselViewChrome-scrollSpeed { color: white; width: 100%; min-width: 100px; @@ -262,7 +273,7 @@ .editableView-container-editing { margin: auto; border: 0px; - color: grey; + color: grey !important; text-align: center; letter-spacing: 2px; outline-color: black; @@ -278,7 +289,8 @@ } .collectionStackingViewChrome-pivotField:hover, - .collectionTreeViewChrome-pivotField:hover { + .collectionTreeViewChrome-pivotField:hover, + .collection3DCarouselViewChrome-scrollSpeed:hover { cursor: text; } diff --git a/src/client/views/collections/CollectionViewChromes.tsx b/src/client/views/collections/CollectionViewChromes.tsx index ac7136d4d..7f1fe7649 100644 --- a/src/client/views/collections/CollectionViewChromes.tsx +++ b/src/client/views/collections/CollectionViewChromes.tsx @@ -88,6 +88,7 @@ export class CollectionViewBaseChrome extends React.Component<CollectionViewChro case CollectionViewType.Freeform: return this._freeform_commands; case CollectionViewType.Time: return this._freeform_commands; case CollectionViewType.Carousel: return this._freeform_commands; + case CollectionViewType.Carousel3D: return this._freeform_commands; } return []; } @@ -214,6 +215,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.Carousel3D: return (<Collection3DCarouselViewChrome 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; } @@ -298,7 +300,7 @@ export class CollectionViewBaseChrome extends React.Component<CollectionViewChro onPointerDown={stopPropagation} onChange={this.viewChanged} value={StrCast(this.props.CollectionView.props.Document._viewType)}> - {Object.values(CollectionViewType).map(type => ["invalid", "docking"].includes(type) ? (null) : ( + {Object.values(CollectionViewType).map(type => [CollectionViewType.Invalid, CollectionViewType.Docking].includes(type) ? (null) : ( <option key={Utils.GenerateGuid()} className="collectionViewBaseChrome-viewOption" @@ -314,7 +316,7 @@ export class CollectionViewBaseChrome extends React.Component<CollectionViewChro render() { const collapsed = this.props.CollectionView.props.Document._chromeStatus !== "enabled"; - const scale = Math.min(1, this.props.CollectionView.props.ScreenToLocalTransform().Scale); + const scale = Math.min(1, this.props.CollectionView.props.ScreenToLocalTransform()?.Scale); return ( <div className="collectionViewChrome-cont" style={{ top: collapsed ? -70 : 0, height: collapsed ? 0 : undefined, @@ -404,7 +406,7 @@ export class CollectionStackingViewChrome extends React.Component<CollectionView @observable private _currentKey: string = ""; @observable private suggestions: string[] = []; - @computed private get descending() { return BoolCast(this.props.CollectionView.props.Document.stackingHeadersSortDescending); } + @computed private get descending() { return StrCast(this.props.CollectionView.props.Document._columnsSort) === "descending"; } @computed get pivotField() { return StrCast(this.props.CollectionView.props.Document._pivotField); } getKeySuggestions = async (value: string): Promise<string[]> => { @@ -448,7 +450,11 @@ export class CollectionStackingViewChrome extends React.Component<CollectionView return true; } - @action toggleSort = () => { this.props.CollectionView.props.Document.stackingHeadersSortDescending = !this.props.CollectionView.props.Document.stackingHeadersSortDescending; }; + @action toggleSort = () => { + this.props.CollectionView.props.Document._columnsSort = + this.props.CollectionView.props.Document._columnsSort === "descending" ? "ascending" : + this.props.CollectionView.props.Document._columnsSort === "ascending" ? undefined : "descending"; + } @action resetValue = () => { this._currentKey = this.pivotField; }; render() { @@ -577,6 +583,43 @@ export class CollectionTreeViewChrome extends React.Component<CollectionViewChro } } +// Enter scroll speed for 3D Carousel +@observer +export class Collection3DCarouselViewChrome extends React.Component<CollectionViewChromeProps> { + @computed get scrollSpeed() { + return this.props.CollectionView.props.Document._autoScrollSpeed; + } + + @action + setValue = (value: string) => { + const numValue = Number(StrCast(value)); + if (numValue > 0) { + this.props.CollectionView.props.Document._autoScrollSpeed = numValue; + return true; + } + return false; + } + + render() { + return ( + <div className="collection3DCarouselViewChrome-cont"> + <div className="collection3DCarouselViewChrome-scrollSpeed-cont"> + <div className="collectionStackingViewChrome-scrollSpeed-label"> + AUTOSCROLL SPEED: + </div> + <div className="collection3DCarouselViewChrome-scrollSpeed"> + <EditableView + GetValue={() => StrCast(this.scrollSpeed)} + oneLine + SetValue={this.setValue} + contents={this.scrollSpeed ? this.scrollSpeed : 1000} /> + </div> + </div> + </div> + ); + } +} + /** * Chrome for grid view. */ @@ -754,4 +797,4 @@ export class CollectionGridViewChrome extends React.Component<CollectionViewChro </div> ); } -}
\ No newline at end of file +} diff --git a/src/client/views/collections/SchemaTable.tsx b/src/client/views/collections/SchemaTable.tsx new file mode 100644 index 000000000..9e3b4d961 --- /dev/null +++ b/src/client/views/collections/SchemaTable.tsx @@ -0,0 +1,614 @@ +import React = require("react"); +import { IconProp } from '@fortawesome/fontawesome-svg-core'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { action, computed, observable } from "mobx"; +import { observer } from "mobx-react"; +import ReactTable, { CellInfo, Column, ComponentPropsGetterR, Resize, SortingRule } from "react-table"; +import "react-table/react-table.css"; +import { Doc, DocListCast, Field, Opt } from "../../../fields/Doc"; +import { Id } from "../../../fields/FieldSymbols"; +import { List } from "../../../fields/List"; +import { listSpec } from "../../../fields/Schema"; +import { SchemaHeaderField } from "../../../fields/SchemaHeaderField"; +import { ComputedField } from "../../../fields/ScriptField"; +import { Cast, FieldValue, NumCast, StrCast, BoolCast } from "../../../fields/Types"; +import { Docs, DocumentOptions } from "../../documents/Documents"; +import { CompileScript, Transformer, ts } from "../../util/Scripting"; +import { Transform } from "../../util/Transform"; +import { undoBatch } from "../../util/UndoManager"; +import { COLLECTION_BORDER_WIDTH } from '../../views/globalCssVariables.scss'; +import { ContextMenu } from "../ContextMenu"; +import '../DocumentDecorations.scss'; +import { CellProps, CollectionSchemaCell, CollectionSchemaCheckboxCell, CollectionSchemaDocCell, CollectionSchemaNumberCell, CollectionSchemaStringCell, CollectionSchemaImageCell, CollectionSchemaListCell, CollectionSchemaDateCell } from "./CollectionSchemaCells"; +import { CollectionSchemaAddColumnHeader, KeysDropdown } from "./CollectionSchemaHeaders"; +import { MovableColumn, MovableRow } from "./CollectionSchemaMovableTableHOC"; +import "./CollectionSchemaView.scss"; +import { CollectionView } from "./CollectionView"; +import { ContentFittingDocumentView } from "../nodes/ContentFittingDocumentView"; +import { emptyFunction, returnZero, returnOne, returnFalse, returnEmptyFilter, emptyPath } from "../../../Utils"; +import { TouchScrollableMenuItem } from "../TouchScrollableMenu"; + + +enum ColumnType { + Any, + Number, + String, + Boolean, + Doc, + Image, + List, + Date +} + +// this map should be used for keys that should have a const type of value +const columnTypes: Map<string, ColumnType> = new Map([ + ["title", ColumnType.String], + ["x", ColumnType.Number], ["y", ColumnType.Number], ["_width", ColumnType.Number], ["_height", ColumnType.Number], + ["_nativeWidth", ColumnType.Number], ["_nativeHeight", ColumnType.Number], ["isPrototype", ColumnType.Boolean], + ["page", ColumnType.Number], ["curPage", ColumnType.Number], ["currentTimecode", ColumnType.Number], ["zIndex", ColumnType.Number] +]); + +export interface SchemaTableProps { + Document: Doc; // child doc + dataDoc?: Doc; + PanelHeight: () => number; + PanelWidth: () => number; + childDocs?: Doc[]; + CollectionView: Opt<CollectionView>; + ContainingCollectionView: Opt<CollectionView>; + ContainingCollectionDoc: Opt<Doc>; + fieldKey: string; + renderDepth: number; + deleteDocument: (document: Doc | Doc[]) => boolean; + addDocument: (document: Doc | Doc[]) => boolean; + moveDocument: (document: Doc | Doc[], targetCollection: Doc | undefined, addDocument: (document: Doc | Doc[]) => boolean) => boolean; + ScreenToLocalTransform: () => Transform; + active: (outsideReaction: boolean) => boolean; + onDrop: (e: React.DragEvent<Element>, options: DocumentOptions, completed?: (() => void) | undefined) => void; + addDocTab: (document: Doc, where: string) => boolean; + pinToPres: (document: Doc) => void; + isSelected: (outsideReaction?: boolean) => boolean; + isFocused: (document: Doc) => boolean; + setFocused: (document: Doc) => void; + setPreviewDoc: (document: Doc) => void; + columns: SchemaHeaderField[]; + documentKeys: any[]; + headerIsEditing: boolean; + openHeader: (column: any, screenx: number, screeny: number) => void; + onPointerDown: (e: React.PointerEvent) => void; + onResizedChange: (newResized: Resize[], event: any) => void; + setColumns: (columns: SchemaHeaderField[]) => void; + reorderColumns: (toMove: SchemaHeaderField, relativeTo: SchemaHeaderField, before: boolean, columnsValues: SchemaHeaderField[]) => void; + changeColumns: (oldKey: string, newKey: string, addNew: boolean) => void; + setHeaderIsEditing: (isEditing: boolean) => void; + changeColumnSort: (columnField: SchemaHeaderField, descending: boolean | undefined) => void; +} + +@observer +export class SchemaTable extends React.Component<SchemaTableProps> { + private DIVIDER_WIDTH = 4; + + @observable _cellIsEditing: boolean = false; + @observable _focusedCell: { row: number, col: number } = { row: 0, col: 0 }; + @observable _openCollections: Array<string> = []; + + @observable _showDoc: Doc | undefined; + @observable _showDataDoc: any = ""; + @observable _showDocPos: number[] = []; + + @observable _showTitleDropdown: boolean = false; + + @computed get previewWidth() { return () => NumCast(this.props.Document.schemaPreviewWidth); } + @computed get previewHeight() { return () => this.props.PanelHeight() - 2 * this.borderWidth; } + @computed get tableWidth() { return this.props.PanelWidth() - 2 * this.borderWidth - this.DIVIDER_WIDTH - this.previewWidth(); } + + @computed get childDocs() { + if (this.props.childDocs) return this.props.childDocs; + + const doc = this.props.dataDoc ? this.props.dataDoc : this.props.Document; + return DocListCast(doc[this.props.fieldKey]); + } + set childDocs(docs: Doc[]) { + const doc = this.props.dataDoc ? this.props.dataDoc : this.props.Document; + doc[this.props.fieldKey] = new List<Doc>(docs); + } + + @computed get textWrappedRows() { + return Cast(this.props.Document.textwrappedSchemaRows, listSpec("string"), []); + } + set textWrappedRows(textWrappedRows: string[]) { + this.props.Document.textwrappedSchemaRows = new List<string>(textWrappedRows); + } + + @computed get resized(): { id: string, value: number }[] { + return this.props.columns.reduce((resized, shf) => { + (shf.width > -1) && resized.push({ id: shf.heading, value: shf.width }); + return resized; + }, [] as { id: string, value: number }[]); + } + @computed get sorted(): SortingRule[] { + return this.props.columns.reduce((sorted, shf) => { + shf.desc && sorted.push({ id: shf.heading, desc: shf.desc }); + return sorted; + }, [] as SortingRule[]); + } + + @action + changeSorting = (col: any) => { + console.log(col.heading); + if (col.desc === undefined) { + // no sorting + this.props.changeColumnSort(col, true); + } else if (col.desc === true) { + // descending sort + this.props.changeColumnSort(col, false); + } else if (col.desc === false) { + // ascending sort + this.props.changeColumnSort(col, undefined); + } + } + + @action + changeTitleMode = () => { console.log("header clicked"); this._showTitleDropdown = !this._showTitleDropdown; } + + @computed get borderWidth() { return Number(COLLECTION_BORDER_WIDTH); } + @computed get tableColumns(): Column<Doc>[] { + + const possibleKeys = this.props.documentKeys.filter(key => this.props.columns.findIndex(existingKey => existingKey.heading.toUpperCase() === key.toUpperCase()) === -1); + const columns: Column<Doc>[] = []; + const tableIsFocused = this.props.isFocused(this.props.Document); + const focusedRow = this._focusedCell.row; + const focusedCol = this._focusedCell.col; + const isEditable = !this.props.headerIsEditing; + + if (this.childDocs.reduce((found, doc) => found || doc.type === "collection", false)) { + columns.push( + { + expander: true, + Header: "", + width: 30, + Expander: (rowInfo) => { + if (rowInfo.original.type === "collection") { + if (rowInfo.isExpanded) return <div className="collectionSchemaView-expander" onClick={() => this.onCloseCollection(rowInfo.original)}><FontAwesomeIcon icon={"sort-up"} size="sm" /></div>; + if (!rowInfo.isExpanded) return <div className="collectionSchemaView-expander" onClick={() => this.onExpandCollection(rowInfo.original)}><FontAwesomeIcon icon={"sort-down"} size="sm" /></div>; + } else { + return null; + } + } + } + ); + } + + const cols = this.props.columns.map(col => { + + const keysDropdown = <KeysDropdown + keyValue={col.heading} + possibleKeys={possibleKeys} + existingKeys={this.props.columns.map(c => c.heading)} + canAddNew={true} + addNew={false} + onSelect={this.props.changeColumns} + setIsEditing={this.props.setHeaderIsEditing} + + // try commenting this out + width={"100%"} + />; + + const icon: IconProp = this.getColumnType(col) === ColumnType.Number ? "hashtag" : this.getColumnType(col) === ColumnType.String ? "font" : + this.getColumnType(col) === ColumnType.Boolean ? "check-square" : this.getColumnType(col) === ColumnType.Doc ? "file" : + this.getColumnType(col) === ColumnType.Image ? "image" : this.getColumnType(col) === ColumnType.List ? "list-ul" : + this.getColumnType(col) === ColumnType.Date ? "calendar" : "align-justify"; + + const headerText = this._showTitleDropdown ? keysDropdown : <div + onClick={this.changeTitleMode} + style={{ + background: col.color, padding: "2px", + letterSpacing: "2px", + textTransform: "uppercase", + display: "flex" + }}> + {col.heading}</div>; + + const sortIcon = col.desc === undefined ? "circle" : col.desc === true ? "caret-down" : "caret-up"; + + const header = + <div //className="collectionSchemaView-header" + //onClick={e => this.props.openHeader(col, menuContent, e.clientX, e.clientY)} + className="collectionSchemaView-menuOptions-wrapper" + style={{ + background: col.color, padding: "2px", + display: "flex" + }}> + <FontAwesomeIcon icon={icon} size="lg" style={{ display: "inline", paddingLeft: "7px" }} /> + <div className="keys-dropdown" + style={{ display: "inline", zIndex: 1000 }}> + {keysDropdown} + </div> + <div onClick={e => this.changeSorting(col)} + style={{ paddingRight: "6px", display: "inline" }}> + <FontAwesomeIcon icon={sortIcon} size="sm" /> + </div> + <div onClick={e => this.props.openHeader(col, e.clientX, e.clientY)} + style={{ float: "right", paddingRight: "6px" }}> + <FontAwesomeIcon icon={"compass"} size="sm" /> + </div> + </div>; + + return { + Header: <MovableColumn columnRenderer={header} columnValue={col} allColumns={this.props.columns} reorderColumns={this.props.reorderColumns} ScreenToLocalTransform={this.props.ScreenToLocalTransform} />, + accessor: (doc: Doc) => doc ? doc[col.heading] : 0, + id: col.heading, + Cell: (rowProps: CellInfo) => { + const rowIndex = rowProps.index; + const columnIndex = this.props.columns.map(c => c.heading).indexOf(rowProps.column.id!); + const isFocused = focusedRow === rowIndex && focusedCol === columnIndex && tableIsFocused; + + const props: CellProps = { + row: rowIndex, + col: columnIndex, + rowProps: rowProps, + isFocused: isFocused, + changeFocusedCellByIndex: this.changeFocusedCellByIndex, + CollectionView: this.props.CollectionView, + ContainingCollection: this.props.ContainingCollectionView, + Document: this.props.Document, + fieldKey: this.props.fieldKey, + renderDepth: this.props.renderDepth, + addDocTab: this.props.addDocTab, + pinToPres: this.props.pinToPres, + moveDocument: this.props.moveDocument, + setIsEditing: this.setCellIsEditing, + isEditable: isEditable, + setPreviewDoc: this.props.setPreviewDoc, + setComputed: this.setComputed, + getField: this.getField, + showDoc: this.showDoc, + }; + + const colType = this.getColumnType(col); + if (colType === ColumnType.Number) return <CollectionSchemaNumberCell {...props} />; + if (colType === ColumnType.String) return <CollectionSchemaStringCell {...props} />; + if (colType === ColumnType.Boolean) return <CollectionSchemaCheckboxCell {...props} />; + if (colType === ColumnType.Doc) return <CollectionSchemaDocCell {...props} />; + if (colType === ColumnType.Image) return <CollectionSchemaImageCell {...props} />; + if (colType === ColumnType.List) return <CollectionSchemaListCell {...props} />; + if (colType === ColumnType.Date) return <CollectionSchemaDateCell {...props} />; + return <CollectionSchemaCell {...props} />; + }, + minWidth: 200, + }; + }); + columns.push(...cols); + + columns.push({ + Header: <CollectionSchemaAddColumnHeader createColumn={this.createColumn} />, + accessor: (doc: Doc) => 0, + id: "add", + Cell: (rowProps: CellInfo) => <></>, + width: 28, + resizable: false + }); + return columns; + } + + constructor(props: SchemaTableProps) { + super(props); + // convert old schema columns (list of strings) into new schema columns (list of schema header fields) + const oldSchemaHeaders = Cast(this.props.Document._schemaHeaders, listSpec("string"), []); + if (oldSchemaHeaders?.length && typeof oldSchemaHeaders[0] !== "object") { + const newSchemaHeaders = oldSchemaHeaders.map(i => typeof i === "string" ? new SchemaHeaderField(i, "#f1efeb") : i); + this.props.Document._schemaHeaders = new List<SchemaHeaderField>(newSchemaHeaders); + } else if (this.props.Document._schemaHeaders === undefined) { + this.props.Document._schemaHeaders = new List<SchemaHeaderField>([new SchemaHeaderField("title", "#f1efeb")]); + } + } + + componentDidMount() { + document.addEventListener("keydown", this.onKeyDown); + } + + componentWillUnmount() { + document.removeEventListener("keydown", this.onKeyDown); + } + + tableAddDoc = (doc: Doc, relativeTo?: Doc, before?: boolean) => { + return Doc.AddDocToList(this.props.Document, this.props.fieldKey, doc, relativeTo, before); + } + + private getTrProps: ComponentPropsGetterR = (state, rowInfo) => { + return !rowInfo ? {} : { + ScreenToLocalTransform: this.props.ScreenToLocalTransform, + addDoc: this.tableAddDoc, + removeDoc: this.props.deleteDocument, + rowInfo, + rowFocused: !this.props.headerIsEditing && rowInfo.index === this._focusedCell.row && this.props.isFocused(this.props.Document), + textWrapRow: this.toggleTextWrapRow, + rowWrapped: this.textWrappedRows.findIndex(id => rowInfo.original[Id] === id) > -1, + dropAction: StrCast(this.props.Document.childDropAction), + addDocTab: this.props.addDocTab + }; + } + + private getTdProps: ComponentPropsGetterR = (state, rowInfo, column, instance) => { + if (!rowInfo || column) return {}; + + const row = rowInfo.index; + //@ts-ignore + const col = this.columns.map(c => c.heading).indexOf(column!.id); + const isFocused = this._focusedCell.row === row && this._focusedCell.col === col && this.props.isFocused(this.props.Document); + // TODO: editing border doesn't work :( + return { + style: { + border: !this.props.headerIsEditing && isFocused ? "2px solid rgb(255, 160, 160)" : "1px solid #f1efeb" + } + }; + } + + @action + onCloseCollection = (collection: Doc): void => { + const index = this._openCollections.findIndex(col => col === collection[Id]); + if (index > -1) this._openCollections.splice(index, 1); + } + + @action onExpandCollection = (collection: Doc) => this._openCollections.push(collection[Id]); + @action setCellIsEditing = (isEditing: boolean) => this._cellIsEditing = isEditing; + + @action + onKeyDown = (e: KeyboardEvent): void => { + if (!this._cellIsEditing && !this.props.headerIsEditing && this.props.isFocused(this.props.Document)) {// && this.props.isSelected(true)) { + const direction = e.key === "Tab" ? "tab" : e.which === 39 ? "right" : e.which === 37 ? "left" : e.which === 38 ? "up" : e.which === 40 ? "down" : ""; + this._focusedCell = this.changeFocusedCellByDirection(direction, this._focusedCell.row, this._focusedCell.col); + + const pdoc = FieldValue(this.childDocs[this._focusedCell.row]); + pdoc && this.props.setPreviewDoc(pdoc); + } + } + + changeFocusedCellByDirection = (direction: string, curRow: number, curCol: number) => { + switch (direction) { + case "tab": return { row: (curRow + 1 === this.childDocs.length ? 0 : curRow + 1), col: curCol + 1 === this.props.columns.length ? 0 : curCol + 1 }; + case "right": return { row: curRow, col: curCol + 1 === this.props.columns.length ? curCol : curCol + 1 }; + case "left": return { row: curRow, col: curCol === 0 ? curCol : curCol - 1 }; + case "up": return { row: curRow === 0 ? curRow : curRow - 1, col: curCol }; + case "down": return { row: curRow + 1 === this.childDocs.length ? curRow : curRow + 1, col: curCol }; + } + return this._focusedCell; + } + + @action + changeFocusedCellByIndex = (row: number, col: number): void => { + if (this._focusedCell.row !== row || this._focusedCell.col !== col) { + this._focusedCell = { row: row, col: col }; + } + this.props.setFocused(this.props.Document); + } + + @undoBatch + createRow = () => { + this.props.addDocument(Docs.Create.TextDocument("", { title: "", _width: 100, _height: 30 })); + } + + @undoBatch + @action + createColumn = () => { + let index = 0; + let found = this.props.columns.findIndex(col => col.heading.toUpperCase() === "New field".toUpperCase()) > -1; + while (found) { + index++; + found = this.props.columns.findIndex(col => col.heading.toUpperCase() === ("New field (" + index + ")").toUpperCase()) > -1; + } + this.props.columns.push(new SchemaHeaderField(`New field ${index ? "(" + index + ")" : ""}`, "#f1efeb")); + } + + @action + getColumnType = (column: SchemaHeaderField): ColumnType => { + // added functionality to convert old column type stuff to new column type stuff -syip + if (column.type && column.type !== 0) { + return column.type; + } + if (columnTypes.get(column.heading)) { + column.type = columnTypes.get(column.heading)!; + return columnTypes.get(column.heading)!; + } + const typesDoc = FieldValue(Cast(this.props.Document.schemaColumnTypes, Doc)); + if (!typesDoc) { + column.type = ColumnType.Any; + return ColumnType.Any; + } + column.type = NumCast(typesDoc[column.heading]); + return NumCast(typesDoc[column.heading]); + } + + @undoBatch + @action + toggleTextwrap = async () => { + const textwrappedRows = Cast(this.props.Document.textwrappedSchemaRows, listSpec("string"), []); + if (textwrappedRows.length) { + this.props.Document.textwrappedSchemaRows = new List<string>([]); + } else { + const docs = DocListCast(this.props.Document[this.props.fieldKey]); + const allRows = docs instanceof Doc ? [docs[Id]] : docs.map(doc => doc[Id]); + this.props.Document.textwrappedSchemaRows = new List<string>(allRows); + } + } + + @action + toggleTextWrapRow = (doc: Doc): void => { + const textWrapped = this.textWrappedRows; + const index = textWrapped.findIndex(id => doc[Id] === id); + + index > -1 ? textWrapped.splice(index, 1) : textWrapped.push(doc[Id]); + + this.textWrappedRows = textWrapped; + } + + @computed + get reactTable() { + const children = this.childDocs; + const hasCollectionChild = children.reduce((found, doc) => found || doc.type === "collection", false); + const expandedRowsList = this._openCollections.map(col => children.findIndex(doc => doc[Id] === col).toString()); + const expanded = {}; + //@ts-ignore + expandedRowsList.forEach(row => expanded[row] = true); + const rerender = [...this.textWrappedRows]; // TODO: get component to rerender on text wrap change without needign to console.log :(((( + + return <ReactTable + style={{ position: "relative" }} + data={children} + page={0} + pageSize={children.length} + showPagination={false} + columns={this.tableColumns} + getTrProps={this.getTrProps} + getTdProps={this.getTdProps} + sortable={false} + TrComponent={MovableRow} + sorted={this.sorted} + expanded={expanded} + resized={this.resized} + onResizedChange={this.props.onResizedChange} + SubComponent={!hasCollectionChild ? undefined : row => (row.original.type !== "collection") ? (null) : + <div className="reactTable-sub"><SchemaTable {...this.props} Document={row.original} dataDoc={undefined} childDocs={undefined} /></div>} + + />; + } + + onContextMenu = (e: React.MouseEvent): void => { + if (!e.isPropagationStopped() && this.props.Document[Id] !== "mainDoc") { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7 + // ContextMenu.Instance.addItem({ description: "Make DB", event: this.makeDB, icon: "table" }); + ContextMenu.Instance.addItem({ description: "Toggle text wrapping", event: this.toggleTextwrap, icon: "table" }); + } + } + + getField = (row: number, col?: number) => { + const docs = this.childDocs; + + row = row % docs.length; + while (row < 0) row += docs.length; + const columns = this.props.columns; + const doc = docs[row]; + if (col === undefined) { + return doc; + } + if (col >= 0 && col < columns.length) { + const column = this.props.columns[col].heading; + return doc[column]; + } + return undefined; + } + + createTransformer = (row: number, col: number): Transformer => { + const self = this; + const captures: { [name: string]: Field } = {}; + + const transformer: ts.TransformerFactory<ts.SourceFile> = context => { + return root => { + function visit(node: ts.Node) { + node = ts.visitEachChild(node, visit, context); + if (ts.isIdentifier(node)) { + const isntPropAccess = !ts.isPropertyAccessExpression(node.parent) || node.parent.expression === node; + const isntPropAssign = !ts.isPropertyAssignment(node.parent) || node.parent.name !== node; + if (isntPropAccess && isntPropAssign) { + if (node.text === "$r") { + return ts.createNumericLiteral(row.toString()); + } else if (node.text === "$c") { + return ts.createNumericLiteral(col.toString()); + } else if (node.text === "$") { + if (ts.isCallExpression(node.parent)) { + // captures.doc = self.props.Document; + // captures.key = self.props.fieldKey; + } + } + } + } + + return node; + } + return ts.visitNode(root, visit); + }; + }; + + // const getVars = () => { + // return { capturedVariables: captures }; + // }; + + return { transformer, /*getVars*/ }; + } + + setComputed = (script: string, doc: Doc, field: string, row: number, col: number): boolean => { + script = + `const $ = (row:number, col?:number) => { + if(col === undefined) { + return (doc as any)[key][row + ${row}]; + } + return (doc as any)[key][row + ${row}][(doc as any)._schemaHeaders[col + ${col}].heading]; + } + return ${script}`; + const compiled = CompileScript(script, { params: { this: Doc.name }, capturedVariables: { doc: this.props.Document, key: this.props.fieldKey }, typecheck: false, transformer: this.createTransformer(row, col) }); + if (compiled.compiled) { + doc[field] = new ComputedField(compiled); + return true; + } + return false; + } + + @action + showDoc = (doc: Doc | undefined, dataDoc?: Doc, screenX?: number, screenY?: number) => { + this._showDoc = doc; + if (dataDoc && screenX && screenY) { + this._showDocPos = this.props.ScreenToLocalTransform().transformPoint(screenX, screenY); + } + } + + onOpenClick = () => { + if (this._showDoc) { + this.props.addDocTab(this._showDoc, "onRight"); + } + } + + getPreviewTransform = (): Transform => { + return this.props.ScreenToLocalTransform().translate(- this.borderWidth - 4 - this.tableWidth, - this.borderWidth); + } + + render() { + const preview = ""; + return <div className="collectionSchemaView-table" onPointerDown={this.props.onPointerDown} onWheel={e => this.props.active(true) && e.stopPropagation()} + onDrop={e => this.props.onDrop(e, {})} onContextMenu={this.onContextMenu} > + {this.reactTable} + <div className="collectionSchemaView-addRow" onClick={() => this.createRow()}>+ new</div> + {!this._showDoc ? (null) : + <div className="collectionSchemaView-documentPreview" //onClick={() => { this.onOpenClick(); }} + style={{ + position: "absolute", width: 150, height: 150, + background: "dimGray", display: "block", top: 0, left: 0, + transform: `translate(${this._showDocPos[0]}px, ${this._showDocPos[1] - 180}px)` + }} + ref="overlay"><ContentFittingDocumentView + Document={this._showDoc} + DataDoc={this._showDataDoc} + NativeHeight={returnZero} + NativeWidth={returnZero} + fitToBox={true} + FreezeDimensions={true} + focus={emptyFunction} + LibraryPath={emptyPath} + renderDepth={this.props.renderDepth} + rootSelected={() => false} + PanelWidth={() => 150} + PanelHeight={() => 150} + ScreenToLocalTransform={this.getPreviewTransform} + docFilters={returnEmptyFilter} + ContainingCollectionDoc={this.props.CollectionView?.props.Document} + ContainingCollectionView={this.props.CollectionView} + moveDocument={this.props.moveDocument} + parentActive={this.props.active} + whenActiveChanged={emptyFunction} + addDocTab={this.props.addDocTab} + pinToPres={this.props.pinToPres} + bringToFront={returnFalse} + ContentScaling={returnOne}> + </ContentFittingDocumentView> + </div>} + </div>; + } +}
\ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx index ae81b4b36..1a2421bfd 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx @@ -10,6 +10,7 @@ import React = require("react"); import { Utils, emptyFunction } from "../../../../Utils"; import { DocumentType } from "../../../documents/DocumentTypes"; import { SnappingManager } from "../../../util/SnappingManager"; +import { Cast } from "../../../../fields/Types"; @observer export class CollectionFreeFormLinksView extends React.Component { @@ -30,8 +31,8 @@ export class CollectionFreeFormLinksView extends React.Component { return drawnPairs; }, [] as { a: DocumentView, b: DocumentView, l: Doc[] }[]); return connections.filter(c => - c.a.props.Document.type === DocumentType.LINK && - c.a.props.pinToPres !== emptyFunction && c.b.props.pinToPres !== emptyFunction // bcz: this prevents links to be drawn to anchors in CollectionTree views -- this is a hack that should be fixed + c.a.props.Document.type === DocumentType.LINK + && !c.a.props.treeViewDoc?.treeViewHideLinkLines && !c.b.props.treeViewDoc?.treeViewHideLinkLines ).map(c => <CollectionFreeFormLinkView key={Utils.GenerateGuid()} A={c.a} B={c.b} LinkDocs={c.l} />); } diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss index d9011c9d3..92aee3776 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss @@ -1,7 +1,6 @@ @import "../../globalCssVariables"; -.collectionfreeformview-none, -.collectionfreeformview-ease { +.collectionfreeformview-none { position: inherit; top: 0; left: 0; @@ -22,10 +21,6 @@ } } -.collectionfreeformview-ease { - transition: transform 500ms; -} - .collectionfreeformview-none { touch-action: none; } diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 936174b52..b81e400b3 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -1,53 +1,51 @@ import { library } from "@fortawesome/fontawesome-svg-core"; -import { faEye, faEyeSlash } from "@fortawesome/free-regular-svg-icons"; +import { faEye } from "@fortawesome/free-regular-svg-icons"; import { faBraille, faChalkboard, faCompass, faCompressArrowsAlt, faExpandArrowsAlt, faFileUpload, faPaintBrush, faTable, faUpload } from "@fortawesome/free-solid-svg-icons"; -import { action, computed, IReactionDisposer, observable, ObservableMap, reaction, runInAction, _allowStateChangesInsideComputed, trace } from "mobx"; +import { action, computed, IReactionDisposer, observable, ObservableMap, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; import { computedFn } from "mobx-utils"; -import { Doc, HeightSym, Opt, WidthSym, DocListCast } from "../../../../fields/Doc"; -import { documentSchema, collectionSchema } from "../../../../fields/documentSchemas"; +import { Doc, DocListCast, HeightSym, Opt, WidthSym } from "../../../../fields/Doc"; +import { collectionSchema, documentSchema } from "../../../../fields/documentSchemas"; import { Id } from "../../../../fields/FieldSymbols"; -import { InkData, InkField, InkTool, PointData } from "../../../../fields/InkField"; +import { InkData, InkField, InkTool } from "../../../../fields/InkField"; import { List } from "../../../../fields/List"; import { RichTextField } from "../../../../fields/RichTextField"; -import { createSchema, listSpec, makeInterface } from "../../../../fields/Schema"; -import { ScriptField, ComputedField } from "../../../../fields/ScriptField"; +import { createSchema, makeInterface } from "../../../../fields/Schema"; +import { ScriptField } from "../../../../fields/ScriptField"; import { BoolCast, Cast, FieldValue, NumCast, ScriptCast, StrCast } from "../../../../fields/Types"; import { TraceMobx } from "../../../../fields/util"; import { GestureUtils } from "../../../../pen-gestures/GestureUtils"; -import { aggregateBounds, intersectRect, returnOne, Utils, returnZero, returnFalse, numberRange } from "../../../../Utils"; +import { aggregateBounds, intersectRect, returnFalse, returnOne, returnZero, Utils } from "../../../../Utils"; import { CognitiveServices } from "../../../cognitive_services/CognitiveServices"; import { DocServer } from "../../../DocServer"; import { Docs, DocUtils } from "../../../documents/Documents"; +import { DocumentType } from "../../../documents/DocumentTypes"; import { DocumentManager } from "../../../util/DocumentManager"; import { DragManager, dropActionType } from "../../../util/DragManager"; import { HistoryUtil } from "../../../util/History"; import { InteractionUtils } from "../../../util/InteractionUtils"; import { SelectionManager } from "../../../util/SelectionManager"; +import { SnappingManager } from "../../../util/SnappingManager"; import { Transform } from "../../../util/Transform"; import { undoBatch, UndoManager } from "../../../util/UndoManager"; import { COLLECTION_BORDER_WIDTH } from "../../../views/globalCssVariables.scss"; +import { Timeline } from "../../animationtimeline/Timeline"; import { ContextMenu } from "../../ContextMenu"; -import { ContextMenuProps } from "../../ContextMenuItem"; +import { ActiveArrowEnd, ActiveArrowStart, ActiveDash, ActiveFillColor, ActiveInkBezierApprox, ActiveInkColor, ActiveInkWidth } from "../../InkingStroke"; import { CollectionFreeFormDocumentView } from "../../nodes/CollectionFreeFormDocumentView"; -import { DocumentViewProps, DocumentView } from "../../nodes/DocumentView"; +import { DocumentLinksButton } from "../../nodes/DocumentLinksButton"; +import { DocumentViewProps } from "../../nodes/DocumentView"; import { FormattedTextBox } from "../../nodes/formattedText/FormattedTextBox"; import { pageSchema } from "../../nodes/ImageBox"; -import PDFMenu from "../../pdf/PDFMenu"; import { CollectionDockingView } from "../CollectionDockingView"; import { CollectionSubView } from "../CollectionSubView"; -import { computePivotLayout, computeTimelineLayout, PoolData, ViewDefBounds, ViewDefResult, computerStarburstLayout, computerPassLayout } from "./CollectionFreeFormLayoutEngines"; +import { CollectionViewType } from "../CollectionView"; +import { computePivotLayout, computerPassLayout, computerStarburstLayout, computeTimelineLayout, PoolData, ViewDefBounds, ViewDefResult } from "./CollectionFreeFormLayoutEngines"; import { CollectionFreeFormRemoteCursors } from "./CollectionFreeFormRemoteCursors"; import "./CollectionFreeFormView.scss"; import MarqueeOptionsMenu from "./MarqueeOptionsMenu"; import { MarqueeView } from "./MarqueeView"; import React = require("react"); -import { CollectionViewType } from "../CollectionView"; -import { Timeline } from "../../animationtimeline/Timeline"; -import { SnappingManager } from "../../../util/SnappingManager"; -import { ActiveInkColor, ActiveInkWidth, ActiveInkBezierApprox } from "../../InkingStroke"; -import { DocumentType } from "../../../documents/DocumentTypes"; -import { DocumentLinksButton } from "../../nodes/DocumentLinksButton"; library.add(faEye as any, faTable, faPaintBrush, faExpandArrowsAlt, faCompressArrowsAlt, faCompass, faUpload, faBraille, faChalkboard, faFileUpload); @@ -63,7 +61,7 @@ export const panZoomSchema = createSchema({ fitToBox: "boolean", _xPadding: "number", // pixels of padding on left/right of collectionfreeformview contents when fitToBox is set _yPadding: "number", // pixels of padding on left/right of collectionfreeformview contents when fitToBox is set - panTransformType: "string", + _viewTransition: "string", scrollHeight: "number", fitX: "number", fitY: "number", @@ -110,9 +108,8 @@ 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 scaleFieldKey() { return this.props.scaleField || "_viewScale"; } 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; private panY = () => this.fitToContent ? (this.contentBounds.y + this.contentBounds.b) / 2 : this.Document._panY || 0; private zoomScaling = () => (this.fitToContentScaling / this.parentScaling) * (this.fitToContent ? @@ -195,7 +192,6 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P return (pt => super.onExternalDrop(e, { x: pt[0], y: pt[1] }))(this.getTransform().transformPoint(e.pageX, e.pageY)); } - @undoBatch @action internalDocDrop(e: Event, de: DragManager.DropEvent, docDragData: DragManager.DocumentDragData, xp: number, yp: number) { if (!super.onInternalDrop(e, de)) return false; @@ -463,7 +459,7 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P case GestureUtils.Gestures.Stroke: const points = ge.points; const B = this.getTransform().transformBounds(ge.bounds.left, ge.bounds.top, ge.bounds.width, ge.bounds.height); - const inkDoc = Docs.Create.InkDocument(ActiveInkColor(), Doc.GetSelectedTool(), ActiveInkWidth(), ActiveInkBezierApprox(), points, + const inkDoc = Docs.Create.InkDocument(ActiveInkColor(), Doc.GetSelectedTool(), ActiveInkWidth(), ActiveInkBezierApprox(), ActiveFillColor(), ActiveArrowStart(), ActiveArrowEnd(), ActiveDash(), points, { title: "ink stroke", x: B.x - Number(ActiveInkWidth()) / 2, y: B.y - Number(ActiveInkWidth()) / 2, _width: B.width + Number(ActiveInkWidth()), _height: B.height + Number(ActiveInkWidth()) }); this.addDocument(inkDoc); e.stopPropagation(); @@ -604,7 +600,6 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P pan = (e: PointerEvent | React.Touch | { clientX: number, clientY: number }): void => { // bcz: theres should be a better way of doing these than referencing these static instances directly MarqueeOptionsMenu.Instance?.fadeOut(true);// I think it makes sense for the marquee menu to go away when panned. -syip2 - PDFMenu.Instance.fadeOut(true); const [dx, dy] = this.getTransform().transformDirection(e.clientX - this._lastX, e.clientY - this._lastY); this.setPan((this.Document._panX || 0) - dx, (this.Document._panY || 0) - dy, undefined, true); @@ -832,7 +827,7 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P } } if (!this.layoutDoc._lockedTransform || this.Document.inOverlay) { - this.Document.panTransformType = panType; + this.Document._viewTransition = panType; const scale = this.getLocalTransform().inverse().Scale; const newPanX = Math.min((1 - 1 / scale) * this.nativeWidth, Math.max(0, panX)); const newPanY = Math.min((this.props.Document.scrollHeight !== undefined ? NumCast(this.Document.scrollHeight) : (1 - 1 / scale) * this.nativeHeight), Math.max(0, panY)); @@ -860,7 +855,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.Document._viewTransition = "transform 500ms"; 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] }; @@ -872,7 +867,7 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P focusDocument = (doc: Doc, willZoom: boolean, scale?: number, afterFocus?: () => boolean) => { const state = HistoryUtil.getState(); - // TODO This technically isn't correct if type !== "doc", as + // TODO This technically isn't correct if type !== "doc", as // currently nothing is done, but we should probably push a new state if (state.type === "doc" && this.Document._panX !== undefined && this.Document._panY !== undefined) { const init = state.initializers![this.Document[Id]]; @@ -905,14 +900,14 @@ 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[this.scaleFieldKey], pt: this.Document.panTransformType }; + const savedState = { px: this.Document._panX, py: this.Document._panY, s: this.Document[this.scaleFieldKey], pt: this.Document._viewTransition }; // if (!willZoom && DocumentView._focusHack.length) { // Doc.BrushDoc(this.props.Document); // !doc.z && NumCast(this.layoutDoc.scale) < 1 && this.scaleAtPt(DocumentView._focusHack, 1); // [NumCast(doc.x), NumCast(doc.y)], 1); // } else { if (DocListCast(this.dataDoc[this.props.fieldKey]).includes(doc)) { - if (!doc.z) this.setPan(newPanX, newPanY, "Ease", true); // docs that are floating in their collection can't be panned to from their collection -- need to propagate the pan to a parent freeform somehow + if (!doc.z) this.setPan(newPanX, newPanY, "transform 500ms", true); // docs that are floating in their collection can't be panned to from their collection -- need to propagate the pan to a parent freeform somehow } Doc.BrushDoc(this.props.Document); this.props.focus(this.props.Document); @@ -925,7 +920,7 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P this.Document._panX = savedState.px; this.Document._panY = savedState.py; this.Document[this.scaleFieldKey] = savedState.s; - this.Document.panTransformType = savedState.pt; + this.Document._viewTransition = savedState.pt; } }, 500); } @@ -1011,7 +1006,7 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P const { z, color, zIndex } = params.pair.layout; return { x: NumCast(x), y: NumCast(y), z: Cast(z, "number"), color: StrCast(color), zIndex: Cast(zIndex, "number"), - transition: StrCast(layoutDoc.transition), opacity: this.Document.editing ? 1 : Cast(opacity, "number", null), + transition: StrCast(layoutDoc.dataTransition), opacity: this.Document.editing ? 1 : Cast(opacity, "number", null), width: Cast(layoutDoc._width, "number"), height: Cast(layoutDoc._height, "number"), pair: params.pair, replica: "" }; } @@ -1206,7 +1201,7 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P private thumbIdentifier?: number; onContextMenu = (e: React.MouseEvent) => { - if (this.props.annotationsKey) return; + if (this.props.annotationsKey || !ContextMenu.Instance) return; const appearance = ContextMenu.Instance.findByDescription("Appearance..."); const appearanceItems = appearance && "subitems" in appearance ? appearance.subitems : []; @@ -1227,7 +1222,7 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P optionItems.push({ description: "Arrange contents in grid", event: this.layoutDocsInGrid, icon: "table" }); if (!Doc.UserDoc().noviceMode) { optionItems.push({ description: (!this.layoutDoc._nativeWidth || !this.layoutDoc._nativeHeight ? "Freeze" : "Unfreeze") + " Aspect", event: this.toggleNativeDimensions, icon: "snowflake" }); - optionItems.push({ description: `${this.Document._LODdisable ? "Enable LOD" : "Disable LOD"}`, event: () => this.Document._LODdisable = !this.Document._LODdisable, icon: "table" }); + optionItems.push({ description: `${this.Document._freeformLOD ? "Enable LOD" : "Disable LOD"}`, event: () => this.Document._freeformLOD = !this.Document._freeformLOD, icon: "table" }); optionItems.push({ description: "Import document", icon: "upload", event: ({ x, y }) => { const input = document.createElement("input"); @@ -1333,9 +1328,9 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P nudge = action((x: number, y: number) => { if (this.props.ContainingCollectionDoc?._viewType !== CollectionViewType.Freeform) { // bcz: this isn't ideal, but want to try it out... this.setPan(NumCast(this.layoutDoc._panX) + this.props.PanelWidth() / 2 * x / this.zoomScaling(), - NumCast(this.layoutDoc._panY) + this.props.PanelHeight() / 2 * (-y) / this.zoomScaling(), "Ease", true); + NumCast(this.layoutDoc._panY) + this.props.PanelHeight() / 2 * (-y) / this.zoomScaling(), "transform 500ms", true); this._nudgeTime = Date.now(); - setTimeout(() => (Date.now() - this._nudgeTime >= 500) && (this.Document.panTransformType = undefined), 500); + setTimeout(() => (Date.now() - this._nudgeTime >= 500) && (this.Document._viewTransition = undefined), 500); return true; } return false; @@ -1354,8 +1349,7 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P <CollectionFreeFormViewPannableContents centeringShiftX={this.centeringShiftX} centeringShiftY={this.centeringShiftY} - easing={this.easing} - transition={Cast(this.layoutDoc.transition, "string", null)} + transition={Cast(this.layoutDoc._viewTransition, "string", null)} viewDefDivClick={this.props.viewDefDivClick} zoomScaling={this.zoomScaling} panX={this.panX} panY={this.panY}> {this.children} @@ -1383,9 +1377,7 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P onPointerDown={this.onPointerDown} onPointerMove={this.onCursorMove} onDrop={this.onExternalDrop.bind(this)} - onDragOver={e => { - e.preventDefault(); - }} + onDragOver={e => e.preventDefault()} onContextMenu={this.onContextMenu} style={{ pointerEvents: this.backgroundEvents ? "all" : undefined, @@ -1394,7 +1386,7 @@ export class CollectionFreeFormView extends CollectionSubView<PanZoomDocument, P width: this.contentScaling ? `${100 / this.contentScaling}%` : "", height: this.contentScaling ? `${100 / this.contentScaling}%` : this.isAnnotationOverlay ? (this.props.Document.scrollHeight ? this.Document.scrollHeight : "100%") : this.props.PanelHeight() }}> - {!this.Document._LODdisable && !this.props.active() && !this.props.isAnnotationOverlay && !this.props.annotationsKey && this.props.renderDepth > 0 ? + {this.Document._freeformLOD && !this.props.active() && !this.props.isAnnotationOverlay && !this.props.annotationsKey && this.props.renderDepth > 0 ? this.placeholder : this.marqueeView} <CollectionFreeFormOverlayView elements={this.elementFunc} /> @@ -1436,7 +1428,6 @@ interface CollectionFreeFormViewPannableContentsProps { panX: () => number; panY: () => number; zoomScaling: () => number; - easing: () => boolean; viewDefDivClick?: ScriptField; children: () => JSX.Element[]; transition?: string; @@ -1445,7 +1436,7 @@ interface CollectionFreeFormViewPannableContentsProps { @observer class CollectionFreeFormViewPannableContents extends React.Component<CollectionFreeFormViewPannableContentsProps>{ render() { - const freeformclass = "collectionfreeformview" + (this.props.viewDefDivClick ? "-viewDef" : (this.props.easing() ? "-ease" : "-none")); + const freeformclass = "collectionfreeformview" + (this.props.viewDefDivClick ? "-viewDef" : "-none"); const cenx = this.props.centeringShiftX(); const ceny = this.props.centeringShiftY(); const panx = -this.props.panX(); @@ -1459,4 +1450,4 @@ class CollectionFreeFormViewPannableContents extends React.Component<CollectionF {this.props.children()} </div>; } -}
\ No newline at end of file +} diff --git a/src/client/views/collections/collectionFreeForm/InkOptionsMenu.scss b/src/client/views/collections/collectionFreeForm/InkOptionsMenu.scss index a7f4d4e53..753de6bef 100644 --- a/src/client/views/collections/collectionFreeForm/InkOptionsMenu.scss +++ b/src/client/views/collections/collectionFreeForm/InkOptionsMenu.scss @@ -1,9 +1,13 @@ .antimodeMenu-button { - .color-preview { + .color-previewI { width: 100%; - height: 100%; + height: 40%; } + .color-previewII { + width: 100%; + height: 100%; + } } @@ -31,6 +35,44 @@ background: #323232; display: block; + } +} + +@media only screen and (max-device-width: 480px) { + .antimodeMenu-button { + font-size: 50%; + + .color-preview { + width: 100%; + height: 100%; + } + + } + + .sketch-picker { + background: #323232; + + .flexbox-fit { + background: #323232; + } + } + + .btn-group { + display: grid; + grid-template-columns: auto auto; + /* Make the buttons appear below each other */ + } + + .btn2-group { + display: block; + background: #323232; + grid-template-columns: auto; + /* Make the buttons appear below each other */ + .antimodeMenu-button { + background: #323232; + display: block; + font-size: 50%; + } } }
\ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/InkOptionsMenu.tsx b/src/client/views/collections/collectionFreeForm/InkOptionsMenu.tsx index 4fac87ca5..f47fca6ac 100644 --- a/src/client/views/collections/collectionFreeForm/InkOptionsMenu.tsx +++ b/src/client/views/collections/collectionFreeForm/InkOptionsMenu.tsx @@ -3,25 +3,48 @@ import AntimodeMenu from "../../AntimodeMenu"; import { observer } from "mobx-react"; import { observable, action, computed } from "mobx"; import "./InkOptionsMenu.scss"; -import { ActiveInkColor, ActiveInkBezierApprox, SetActiveInkWidth, SetActiveInkColor, SetActiveBezierApprox } from "../../InkingStroke"; +import { ActiveInkColor, ActiveInkBezierApprox, ActiveFillColor, ActiveArrowStart, ActiveArrowEnd, SetActiveInkWidth, SetActiveInkColor, SetActiveBezierApprox, SetActiveFillColor, SetActiveArrowStart, SetActiveArrowEnd, ActiveDash, SetActiveDash } from "../../InkingStroke"; import { Scripting } from "../../../util/Scripting"; import { InkTool } from "../../../../fields/InkField"; import { ColorState } from "react-color"; import { Utils } from "../../../../Utils"; import GestureOverlay from "../../GestureOverlay"; import { Doc } from "../../../../fields/Doc"; +import { SelectionManager } from "../../../util/SelectionManager"; +import { DocumentView } from "../../../views/nodes/DocumentView"; +import { Document } from "../../../../fields/documentSchemas"; +import { DocumentType } from "../../../documents/DocumentTypes"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { IconProp, library } from '@fortawesome/fontawesome-svg-core'; +import { faBold, faItalic, faChevronLeft, faUnderline, faStrikethrough, faSubscript, faSuperscript, faIndent, faEyeDropper, faCaretDown, faPalette, faArrowsAlt, faHighlighter, faLink, faPaintRoller, faSleigh, faBars, faFillDrip, faBrush, faPenNib, faShapes, faArrowLeft, faEllipsisH, faBezierCurve, } from "@fortawesome/free-solid-svg-icons"; + +library.add(faBold, faItalic, faChevronLeft, faUnderline, faStrikethrough, faSuperscript, faSubscript, faIndent, faEyeDropper, faCaretDown, faPalette, faArrowsAlt, faHighlighter, faLink, faPaintRoller, faBars, faFillDrip, faBrush, faPenNib, faShapes, faArrowLeft, faEllipsisH, faBezierCurve); + + @observer export default class InkOptionsMenu extends AntimodeMenu { static Instance: InkOptionsMenu; - private _palette = ["D0021B", "F5A623", "F8E71C", "8B572A", "7ED321", "417505", "9013FE", "4A90E2", "50E3C2", "B8E986", "000000", "4A4A4A", "9B9B9B", "FFFFFF"]; - private _width = ["1", "5", "10", "100", "200", "300"]; - private _buttons = ["circle", "triangle", "rectangle", "arrow", "line"]; - private _icons = ["O", "∆", "ロ", "➜", "-"]; + private _palette = ["#D0021B", "#F5A623", "#F8E71C", "#8B572A", "#7ED321", "#417505", "#9013FE", "#4A90E2", "#50E3C2", "#B8E986", "#000000", "#4A4A4A", "#9B9B9B", "#FFFFFF", "none"]; + private _width = ["1", "5", "10", "100"]; + // private _buttons = ["circle", "triangle", "rectangle", "arrow", "line"]; + // private _icons = ["O", "∆", "ロ", "➜", "-"]; + private _buttons = ["circle", "triangle", "rectangle", "line", "noRec", "",]; + private _icons = ["O", "∆", "ロ", "⎯", "✖︎", " "]; + //arrowStart and arrowEnd must match and defs must exist in Inking Stroke + private _arrowStart = ["arrowHead", "arrowHead", "dot", "dot", "none"]; + private _arrowEnd = ["none", "arrowEnd", "none", "dot", "none"]; + private _arrowIcons = ["→", "↔︎", "•", "••", " "]; @observable _colorBtn = false; @observable _widthBtn = false; + @observable _fillBtn = false; + @observable _arrowBtn = false; + @observable _dashBtn = false; + @observable _shapeBtn = false; + + constructor(props: Readonly<{}>) { super(props); @@ -29,18 +52,106 @@ export default class InkOptionsMenu extends AntimodeMenu { this._canFade = false; // don't let the inking menu fade away } + getColors = () => { + return this._palette; + } + @action - changeColor = (color: string) => { + changeArrow = (arrowStart: string, arrowEnd: string) => { + SetActiveArrowStart(arrowStart); + SetActiveArrowEnd(arrowEnd); + } + + @action + changeColor = (color: string, type: string) => { const col: ColorState = { hex: color, hsl: { a: 0, h: 0, s: 0, l: 0, source: "" }, hsv: { a: 0, h: 0, s: 0, v: 0, source: "" }, rgb: { a: 0, r: 0, b: 0, g: 0, source: "" }, oldHue: 0, source: "", }; - SetActiveInkColor(Utils.colorString(col)); + if (type === "color") { + SetActiveInkColor(Utils.colorString(col)); + } else if (type === "fill") { + SetActiveFillColor(Utils.colorString(col)); + } } @action + editProperties = (value: any, field: string) => { + SelectionManager.SelectedDocuments().forEach(action((element: DocumentView) => { + const doc = Document(element.rootDoc); + if (doc.type === DocumentType.INK) { + switch (field) { + case "width": + doc.strokeWidth = Number(value); + break; + case "color": + doc.color = String(value); + break; + case "fill": + doc.fillColor = String(value); + break; + case "bezier": + // doc.strokeBezier === 300 ? doc.strokeBezier = 0 : doc.strokeBezier = 300; + break; + case "arrowStart": + doc.arrowStart = String(value); + break; + case "arrowEnd": + doc.arrowEnd = String(value); + break; + case "dash": + doc.dash = Number(value); + default: + break; + } + } + })); + } + + + @action changeBezier = (e: React.PointerEvent): void => { SetActiveBezierApprox(!ActiveInkBezierApprox() ? "300" : ""); + this.editProperties(0, "bezier"); + } + @action + changeDash = (e: React.PointerEvent): void => { + SetActiveDash(ActiveDash() === "0" ? "2" : "0"); + this.editProperties(ActiveDash(), "dash"); + } + + @computed get arrowPicker() { + var currIcon; + for (var i = 0; i < this._arrowStart.length; i++) { + if (this._arrowStart[i] === ActiveArrowStart() && this._arrowEnd[i] === ActiveArrowEnd()) { + currIcon = this._arrowIcons[i]; + if (this._arrowIcons[i] === " ") { + currIcon = "➤"; + } + } + } + var arrowPicker = <button + className="antimodeMenu-button" + key="arrow" + onPointerDown={action(e => this._arrowBtn = !this._arrowBtn)} + style={{ backgroundColor: this._arrowBtn ? "121212" : "" }}> + {currIcon} + </button>; + if (this._arrowBtn) { + arrowPicker = <div className="btn2-group" key="arrows"> + {arrowPicker} + {this._arrowStart.map((arrowStart, i) => { + return <button + className="antimodeMenu-button" + key={arrowStart} + onPointerDown={action(() => { SetActiveArrowStart(arrowStart); SetActiveArrowEnd(this._arrowEnd[i]); this.editProperties(arrowStart, "arrowStart"), this.editProperties(this._arrowEnd[i], "arrowEnd"); this._arrowBtn = false; })} + style={{ backgroundColor: this._arrowBtn ? "121212" : "" }}> + {this._arrowIcons[i]} + </button>; + })} + </div>; + } + return arrowPicker; } @computed get widthPicker() { @@ -49,7 +160,7 @@ export default class InkOptionsMenu extends AntimodeMenu { key="width" onPointerDown={action(e => this._widthBtn = !this._widthBtn)} style={{ backgroundColor: this._widthBtn ? "121212" : "" }}> - W + <FontAwesomeIcon icon="bars" size="lg" /> </button>; if (this._widthBtn) { widthPicker = <div className="btn2-group" key="width"> @@ -58,7 +169,7 @@ export default class InkOptionsMenu extends AntimodeMenu { return <button className="antimodeMenu-button" key={wid} - onPointerDown={action(() => { SetActiveInkWidth(wid); this._widthBtn = false; })} + onPointerDown={action(() => { SetActiveInkWidth(wid); this._widthBtn = false; this.editProperties(wid, "width"); })} style={{ backgroundColor: this._widthBtn ? "121212" : "" }}> {wid} </button>; @@ -68,6 +179,8 @@ export default class InkOptionsMenu extends AntimodeMenu { return widthPicker; } + + @computed get colorPicker() { var colorPicker = <button className="antimodeMenu-button" @@ -75,7 +188,9 @@ export default class InkOptionsMenu extends AntimodeMenu { title="colorChanger" onPointerDown={action(e => this._colorBtn = !this._colorBtn)} style={{ backgroundColor: this._colorBtn ? "121212" : "" }}> - <div className="color-preview" style={{ backgroundColor: ActiveInkColor() ?? "121212" }}></div> + <FontAwesomeIcon icon="pen-nib" size="lg" /> + <div className="color-previewI" style={{ backgroundColor: ActiveInkColor() ?? "121212" }}></div> + </button>; if (this._colorBtn) { colorPicker = <div className="btn-group" key="color"> @@ -84,9 +199,10 @@ export default class InkOptionsMenu extends AntimodeMenu { return <button className="antimodeMenu-button" key={color} - onPointerDown={action(() => { this.changeColor(color); this._colorBtn = false; })} + onPointerDown={action(() => { this.changeColor(color, "color"); this._colorBtn = false; this.editProperties(color, "color"); })} style={{ backgroundColor: this._colorBtn ? "121212" : "" }}> - <div className="color-preview" style={{ backgroundColor: color }}></div> + {/* <FontAwesomeIcon icon="pen-nib" size="lg" /> */} + <div className="color-previewII" style={{ backgroundColor: color }}></div> </button>; })} </div>; @@ -94,15 +210,75 @@ export default class InkOptionsMenu extends AntimodeMenu { return colorPicker; } - @computed get shapeButtons() { - return this._buttons.map((btn, i) => <button + @computed get fillPicker() { + var fillPicker = <button className="antimodeMenu-button" - title={`Draw ${btn}`} - key={i} - onPointerDown={action(e => GestureOverlay.Instance.InkShape = btn)} - style={{ backgroundColor: btn === GestureOverlay.Instance.InkShape ? "121212" : "" }}> - {this._icons[i]} - </button>); + key="fill" + title="fillChanger" + onPointerDown={action(e => this._fillBtn = !this._fillBtn)} + style={{ backgroundColor: this._fillBtn ? "121212" : "" }}> + <FontAwesomeIcon icon="fill-drip" size="lg" /> + <div className="color-previewI" style={{ backgroundColor: ActiveFillColor() ?? "121212" }}></div> + </button>; + if (this._fillBtn) { + fillPicker = <div className="btn-group" key="fill"> + {fillPicker} + {this._palette.map(color => { + return <button + className="antimodeMenu-button" + key={color} + onPointerDown={action(() => { this.changeColor(color, "fill"); this._fillBtn = false; this.editProperties(color, "fill"); })} + style={{ backgroundColor: this._fillBtn ? "121212" : "" }}> + <div className="color-previewII" style={{ backgroundColor: color }}></div> + </button>; + })} + + </div>; + } + return fillPicker; + } + + @computed get shapePicker() { + var currIcon; + if (GestureOverlay.Instance.InkShape === "") { + currIcon = <FontAwesomeIcon icon="shapes" size="lg" />; + } else { + for (var i = 0; i < this._icons.length; i++) { + if (GestureOverlay.Instance.InkShape === this._buttons[i]) { + currIcon = this._icons[i]; + } + } + } + var shapePicker = <button + className="antimodeMenu-button" + key="shape" + onPointerDown={action(e => this._shapeBtn = !this._shapeBtn)} + style={{ backgroundColor: this._shapeBtn ? "121212" : "" }}> + {currIcon} + </button>; + if (this._shapeBtn) { + shapePicker = <div className="btn2-group" key="shape"> + {shapePicker} + {this._buttons.map((btn, i) => { + var ttl = btn; + if (btn === "") { + ttl = "no shape"; + } + if (btn === "noRec") { + ttl = "disable shape recognition"; + } + return <button + className="antimodeMenu-button" + title={`Draw ${btn}`} + key={ttl} + onPointerDown={action((e) => { GestureOverlay.Instance.InkShape = btn; this._shapeBtn = false; })} + style={{ backgroundColor: this._shapeBtn ? "121212" : "" }}> + {this._icons[i]} + </button>; + })} + </div>; + } + return shapePicker; } @computed get bezierButton() { @@ -112,16 +288,35 @@ export default class InkOptionsMenu extends AntimodeMenu { key="bezier" onPointerDown={e => this.changeBezier(e)} style={{ backgroundColor: ActiveInkBezierApprox() ? "121212" : "" }}> - B + <FontAwesomeIcon icon="bezier-curve" size="lg" /> + + </button>; + } + + @computed get dashButton() { + return <button + className="antimodeMenu-button" + title="dash changer" + key="dash" + onPointerDown={e => this.changeDash(e)} + style={{ backgroundColor: ActiveDash() !== "0" ? "121212" : "" }}> + <FontAwesomeIcon icon="ellipsis-h" size="lg" /> + </button>; } render() { const buttons = [ - ...this.shapeButtons, + // <button className="antimodeMenu-button" title="Drag" key="drag" onPointerDown={e => this.dragStart(e)}> + // <FontAwesomeIcon icon="arrows-alt" size="lg" /> + // </button>, + this.shapePicker, this.bezierButton, this.widthPicker, this.colorPicker, + this.fillPicker, + this.arrowPicker, + this.dashButton, ]; return this.getElement(buttons); } @@ -134,4 +329,4 @@ Scripting.addGlobal(function activatePen(penBtn: any) { Doc.SetSelectedTool(InkTool.None); InkOptionsMenu.Instance.fadeOut(true); } -});
\ No newline at end of file +}); diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx index 1bc7c6fb5..97ed74c10 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -20,8 +20,6 @@ import { CollectionView } from "../CollectionView"; import MarqueeOptionsMenu from "./MarqueeOptionsMenu"; import "./MarqueeView.scss"; import React = require("react"); -import { DateField } from "../../../../fields/DateField"; -import { DocServer } from "../../../DocServer"; interface MarqueeViewProps { getContainerTransform: () => Transform; @@ -260,6 +258,10 @@ export class MarqueeView extends React.Component<SubCollectionViewProps & Marque e.preventDefault(); } } + clearSelection() { + if (window.getSelection) { window.getSelection()?.removeAllRanges(); } + else if (document.getSelection()) { document.getSelection()?.empty(); } + } setPreviewCursor = action((x: number, y: number, drag: boolean) => { if (drag) { @@ -275,6 +277,7 @@ export class MarqueeView extends React.Component<SubCollectionViewProps & Marque this._downX = x; this._downY = y; PreviewCursor.Show(x, y, this.onKeyPress, this.props.addLiveTextDocument, this.props.getTransform, this.props.addDocument, this.props.nudge); + this.clearSelection(); } }); @@ -349,7 +352,6 @@ export class MarqueeView extends React.Component<SubCollectionViewProps & Marque backgroundColor: this.props.isAnnotationOverlay ? "#00000015" : isBackground ? "cyan" : undefined, _width: bounds.width, _height: bounds.height, - _LODdisable: true, title: "a nested collection", }); selected.forEach(d => d.context = newCollection); diff --git a/src/client/views/linking/LinkMenu.scss b/src/client/views/linking/LinkMenu.scss index c372e7098..6468ccd3d 100644 --- a/src/client/views/linking/LinkMenu.scss +++ b/src/client/views/linking/LinkMenu.scss @@ -15,7 +15,7 @@ } .linkMenu-group { - border-bottom: 0.5px solid lightgray; + border-bottom: 0.5px solid lightgray; padding: 5px 0; @@ -30,9 +30,11 @@ p { background-color: lightgray; } + p.expand-one { width: calc(100% - 26px); } + .linkEditor-tableButton { display: block; } @@ -50,7 +52,4 @@ display: none; } } -} - - - +}
\ No newline at end of file diff --git a/src/client/views/linking/LinkMenu.tsx b/src/client/views/linking/LinkMenu.tsx index 0fcc0f0b9..c672511ac 100644 --- a/src/client/views/linking/LinkMenu.tsx +++ b/src/client/views/linking/LinkMenu.tsx @@ -10,6 +10,7 @@ import { LinkMenuGroup } from "./LinkMenuGroup"; import { faTrash } from '@fortawesome/free-solid-svg-icons'; import { library } from "@fortawesome/fontawesome-svg-core"; import { DocumentLinksButton } from "../nodes/DocumentLinksButton"; +import { LinkDocPreview } from "../nodes/LinkDocPreview"; library.add(faTrash); @@ -28,7 +29,14 @@ export class LinkMenu extends React.Component<Props> { @action onClick = (e: PointerEvent) => { - if (!Array.from(this._linkMenuRef?.getElementsByTagName((e.target as HTMLElement).tagName) || []).includes(e.target as any)) { + + LinkDocPreview.LinkInfo = undefined; + + if (this._linkMenuRef?.contains(e.target as any)) { + DocumentLinksButton.EditLink = undefined; + } + + if (this._linkMenuRef && !this._linkMenuRef.contains(e.target as any)) { DocumentLinksButton.EditLink = undefined; } } @@ -70,7 +78,8 @@ export class LinkMenu extends React.Component<Props> { render() { const sourceDoc = this.props.docView.props.Document; const groups: Map<string, Doc[]> = LinkManager.Instance.getRelatedGroupedLinks(sourceDoc); - return <div className="linkMenu-list" ref={(r) => this._linkMenuRef = r} style={{ left: this.props.location[0], top: this.props.location[1] }}> + return <div className="linkMenu-list" + ref={(r) => this._linkMenuRef = r} style={{ left: this.props.location[0], top: this.props.location[1] }}> {!this._editingLink ? this.renderAllGroups(groups) : <LinkEditor sourceDoc={this.props.docView.props.Document} linkDoc={this._editingLink} showLinks={action(() => this._editingLink = undefined)} /> diff --git a/src/client/views/linking/LinkMenuGroup.tsx b/src/client/views/linking/LinkMenuGroup.tsx index 89deb3a55..7892d381b 100644 --- a/src/client/views/linking/LinkMenuGroup.tsx +++ b/src/client/views/linking/LinkMenuGroup.tsx @@ -80,11 +80,11 @@ export class LinkMenuGroup extends React.Component<LinkMenuGroupProps> { return ( <div className="linkMenu-group"> - <div className="linkMenu-group-name"> + {/* <div className="linkMenu-group-name"> <p ref={this._drag} onPointerDown={this.onLinkButtonDown} className={this.props.groupType === "*" || this.props.groupType === "" ? "" : "expand-one"} > {this.props.groupType}:</p> {this.props.groupType === "*" || this.props.groupType === "" ? <></> : this.viewGroupAsTable(this.props.groupType)} - </div> + </div> */} <div className="linkMenu-group-wrapper"> {groupItems} </div> diff --git a/src/client/views/linking/LinkMenuItem.scss b/src/client/views/linking/LinkMenuItem.scss index fd0954f65..e3ce69cd7 100644 --- a/src/client/views/linking/LinkMenuItem.scss +++ b/src/client/views/linking/LinkMenuItem.scss @@ -5,7 +5,7 @@ position: relative; display: flex; font-size: 12px; - + .linkMenu-name { position: relative; @@ -22,7 +22,7 @@ .linkMenu-item-content { width: 100%; } - + .link-metadata { padding: 0 10px 0 16px; margin-bottom: 4px; @@ -35,11 +35,13 @@ .linkMenu-item-buttons { display: flex; } + .linkMenu-item-content { &.expand-two p { width: calc(100% - 52px); background-color: lightgray; } + &.expand-three p { width: calc(100% - 84px); background-color: lightgray; @@ -49,11 +51,11 @@ } .linkMenu-item-buttons { - display: none; position: absolute; top: 50%; right: 0; transform: translateY(-50%); + display: none; .button { width: 20px; @@ -61,7 +63,6 @@ margin: 0; margin-right: 6px; border-radius: 50%; - cursor: pointer; pointer-events: auto; background-color: $dark-color; color: $light-color; @@ -80,8 +81,10 @@ &:last-child { margin-right: 0; } + &:hover { background: $main-accent; + cursor: grab; } } }
\ No newline at end of file diff --git a/src/client/views/linking/LinkMenuItem.tsx b/src/client/views/linking/LinkMenuItem.tsx index edc18b6a9..04cd83ee0 100644 --- a/src/client/views/linking/LinkMenuItem.tsx +++ b/src/client/views/linking/LinkMenuItem.tsx @@ -1,5 +1,5 @@ import { library } from '@fortawesome/fontawesome-svg-core'; -import { faArrowRight, faChevronDown, faChevronUp, faEdit, faEye, faTimes } from '@fortawesome/free-solid-svg-icons'; +import { faArrowRight, faChevronDown, faChevronUp, faEdit, faEye, faTimes, faPencilAlt } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { action, observable } from 'mobx'; import { observer } from "mobx-react"; @@ -13,7 +13,9 @@ import React = require("react"); import { DocumentManager } from '../../util/DocumentManager'; import { setupMoveUpEvents, emptyFunction } from '../../../Utils'; import { DocumentView } from '../nodes/DocumentView'; -library.add(faEye, faEdit, faTimes, faArrowRight, faChevronDown, faChevronUp); +import { DocumentLinksButton } from '../nodes/DocumentLinksButton'; +import { LinkDocPreview } from '../nodes/LinkDocPreview'; +library.add(faEye, faEdit, faTimes, faArrowRight, faChevronDown, faChevronUp, faPencilAlt); interface LinkMenuItemProps { @@ -69,6 +71,8 @@ export class LinkMenuItem extends React.Component<LinkMenuItemProps> { private _eleClone: any; _editRef = React.createRef<HTMLDivElement>(); + _buttonRef = React.createRef<HTMLDivElement>(); + @observable private _showMore: boolean = false; @action toggleShowMore(e: React.PointerEvent) { e.stopPropagation(); this._showMore = !this._showMore; } @@ -95,6 +99,7 @@ export class LinkMenuItem extends React.Component<LinkMenuItemProps> { return (<div className="link-metadata">{mdRows}</div>); } + @action onLinkButtonDown = (e: React.PointerEvent): void => { this._downX = e.clientX; this._downY = e.clientY; @@ -104,6 +109,10 @@ export class LinkMenuItem extends React.Component<LinkMenuItemProps> { document.addEventListener("pointermove", this.onLinkButtonMoved); document.removeEventListener("pointerup", this.onLinkButtonUp); document.addEventListener("pointerup", this.onLinkButtonUp); + + if (this._buttonRef && this._buttonRef.current?.contains(e.target as any)) { + LinkDocPreview.LinkInfo = undefined; + } } onLinkButtonUp = (e: PointerEvent): void => { @@ -124,7 +133,10 @@ export class LinkMenuItem extends React.Component<LinkMenuItemProps> { e.stopPropagation(); } + @action onContextMenu = (e: React.MouseEvent) => { + DocumentLinksButton.EditLink = undefined; + LinkDocPreview.LinkInfo = undefined; e.preventDefault(); ContextMenu.Instance.addItem({ description: "Follow Default Link", event: () => this.followDefault(), icon: "arrow-right" }); ContextMenu.Instance.displayMenu(e.clientX, e.clientY); @@ -132,9 +144,20 @@ export class LinkMenuItem extends React.Component<LinkMenuItemProps> { @action.bound async followDefault() { + console.log("FOLLOWWW"); + DocumentLinksButton.EditLink = undefined; + LinkDocPreview.LinkInfo = undefined; DocumentManager.Instance.FollowLink(this.props.linkDoc, this.props.sourceDoc, doc => this.props.addDocTab(doc, "onRight"), false); } + @action + deleteLink = (): void => { + LinkManager.Instance.deleteLink(this.props.linkDoc); + //this.props.showLinks(); + LinkDocPreview.LinkInfo = undefined; + DocumentLinksButton.EditLink = undefined; + } + render() { const keys = LinkManager.Instance.getMetadataKeysInGroup(this.props.groupType);//groupMetadataKeys.get(this.props.groupType); const canExpand = keys ? keys.length > 0 : false; @@ -142,13 +165,25 @@ export class LinkMenuItem extends React.Component<LinkMenuItemProps> { return ( <div className="linkMenu-item"> <div className={canExpand ? "linkMenu-item-content expand-three" : "linkMenu-item-content expand-two"}> - <div ref={this._drag} className="linkMenu-name" title="drag to view target. click to customize." onPointerDown={this.onLinkButtonDown}> + <div ref={this._drag} className="linkMenu-name" //title="drag to view target. click to customize." + onPointerLeave={action(() => LinkDocPreview.LinkInfo = undefined)} + onPointerEnter={action(e => this.props.linkDoc && (LinkDocPreview.LinkInfo = { + addDocTab: this.props.addDocTab, + linkSrc: this.props.sourceDoc, + linkDoc: this.props.linkDoc, + Location: [e.clientX, e.clientY + 20] + }))} + onPointerDown={this.onLinkButtonDown}> <p >{StrCast(this.props.destinationDoc.title)}</p> - <div className="linkMenu-item-buttons"> + <div className="linkMenu-item-buttons" ref={this._buttonRef} > {canExpand ? <div title="Show more" className="button" onPointerDown={e => this.toggleShowMore(e)}> <FontAwesomeIcon className="fa-icon" icon={this._showMore ? "chevron-up" : "chevron-down"} size="sm" /></div> : <></>} - <div title="Edit link" className="button" ref={this._editRef} onPointerDown={this.onEdit}><FontAwesomeIcon className="fa-icon" icon="edit" size="sm" /></div> - <div title="Follow link" className="button" onClick={this.followDefault} onContextMenu={this.onContextMenu}> + + {/* <div title="Edit link" className="button" ref={this._editRef} onPointerDown={this.onEdit}> + <FontAwesomeIcon className="fa-icon" icon="pencil-alt" size="sm" /></div> */} + <div title="Delete link" className="button" onPointerDown={this.deleteLink}> + <FontAwesomeIcon className="fa-icon" icon="trash" size="sm" /></div> + <div title="Follow link" className="button" onPointerDown={this.followDefault} onContextMenu={this.onContextMenu}> <FontAwesomeIcon className="fa-icon" icon="arrow-right" size="sm" /> </div> </div> diff --git a/src/client/views/nodes/AudioBox.scss b/src/client/views/nodes/AudioBox.scss index 53b54d7e4..c959b79f5 100644 --- a/src/client/views/nodes/AudioBox.scss +++ b/src/client/views/nodes/AudioBox.scss @@ -1,141 +1,169 @@ -.audiobox-container, .audiobox-container-interactive { +.audiobox-container, +.audiobox-container-interactive { width: 100%; height: 100%; position: inherit; - display:flex; + display: flex; pointer-events: all; - cursor:default; + cursor: default; + .audiobox-buttons { display: flex; width: 100%; align-items: center; } + .audiobox-handle { - width:20px; - height:100%; - display:inline-block; + width: 20px; + height: 100%; + display: inline-block; } - .audiobox-control, .audiobox-control-interactive { - top:0; + + .audiobox-control, + .audiobox-control-interactive { + top: 0; max-height: 32px; width: 100%; - display:inline-block; + display: inline-block; pointer-events: none; } + .audiobox-control-interactive { pointer-events: all; } + .audiobox-record { pointer-events: all; - width:100%; - height:100%; + width: 100%; + height: 100%; position: relative; pointer-events: none; } + .audiobox-record-interactive { pointer-events: all; - width:100%; - height:100%; + width: 100%; + height: 100%; position: relative; } + .audiobox-controls { - width:100%; - height:100%; + width: 100%; + height: 100%; position: relative; display: flex; padding-left: 2px; + .audiobox-player { - margin-top:auto; - margin-bottom:auto; - width:100%; + margin-top: auto; + margin-bottom: auto; + width: 100%; height: 80%; position: relative; padding-right: 5px; display: flex; - .audiobox-playhead, .audiobox-dictation { + + .audiobox-playhead, + .audiobox-dictation { position: relative; margin-top: auto; margin-bottom: auto; width: 25px; padding: 2px; } + .audiobox-dictation { align-items: center; display: inherit; background: dimgray; } + .audiobox-timeline { - position:relative; - height:100%; - width:100%; + position: relative; + height: 100%; + width: 100%; background: white; border: gray solid 1px; border-radius: 3px; + .audiobox-current { width: 1px; - height:100%; + height: 100%; background-color: red; position: absolute; } - .audiobox-linker, .audiobox-linker-mini { - position:absolute; - width:15px; - min-height:10px; - height:15px; - margin-left:-2.55px; - background:gray; + + .audiobox-linker, + .audiobox-linker-mini { + position: absolute; + width: 15px; + min-height: 10px; + height: 15px; + margin-left: -2.55px; + background: gray; border-radius: 100%; - opacity:0.9; + opacity: 0.9; background-color: transparent; box-shadow: black 2px 2px 1px; + .linkAnchorBox-cont { position: relative !important; - height: 100% !important; + height: 100% !important; width: 100% !important; - left:unset !important; - top:unset !important; + left: unset !important; + top: unset !important; } } + .audiobox-linker-mini { - width:8px; - min-height:8px; - height:8px; + width: 8px; + min-height: 8px; + height: 8px; box-shadow: black 1px 1px 1px; margin-left: -1; margin-top: -2; + .linkAnchorBox-cont { position: relative !important; - height: 100% !important; + height: 100% !important; width: 100% !important; - left:unset !important; - top:unset !important; + left: unset !important; + top: unset !important; } } - .audiobox-linker:hover, .audiobox-linker-mini:hover { - opacity:1; + + .audiobox-linker:hover, + .audiobox-linker-mini:hover { + opacity: 1; } - .audiobox-marker-container, .audiobox-marker-minicontainer { - position:absolute; - width:10px; - height:90%; - top:2.5%; - background:gray; + + .audiobox-marker-container, + .audiobox-marker-minicontainer { + position: absolute; + width: 10px; + height: 90%; + top: 2.5%; + background: gray; border-radius: 5px; box-shadow: black 2px 2px 1px; + .audiobox-marker { - position:relative; + position: relative; height: calc(100% - 15px); margin-top: 15px; } + .audio-marker:hover { border: orange 2px solid; } } + .audiobox-marker-minicontainer { - width:5px; + width: 5px; border-radius: 1px; + .audiobox-marker { - position:relative; + position: relative; height: calc(100% - 8px); margin-top: 8px; } @@ -143,4 +171,27 @@ } } } +} + + +@media only screen and (max-device-width: 480px) { + .audiobox-dictation { + font-size: 5em; + display: flex; + width: 100; + justify-content: center; + flex-direction: column; + align-items: center; + } + + .audiobox-container .audiobox-record, + .audiobox-container-interactive .audiobox-record { + font-size: 3em; + } + + .audiobox-container .audiobox-controls .audiobox-player .audiobox-playhead, + .audiobox-container .audiobox-controls .audiobox-player .audiobox-dictation, + .audiobox-container-interactive .audiobox-controls .audiobox-player .audiobox-playhead { + width: 70px; + } }
\ No newline at end of file diff --git a/src/client/views/nodes/AudioBox.tsx b/src/client/views/nodes/AudioBox.tsx index 1a935d9b0..d5288fff6 100644 --- a/src/client/views/nodes/AudioBox.tsx +++ b/src/client/views/nodes/AudioBox.tsx @@ -161,7 +161,7 @@ export class AudioBox extends ViewBoxBaseComponent<FieldViewProps, AudioDocument const funcs: ContextMenuProps[] = []; funcs.push({ description: (this.layoutDoc.playOnSelect ? "Don't play" : "Play") + " when document selected", event: () => this.layoutDoc.playOnSelect = !this.layoutDoc.playOnSelect, icon: "expand-arrows-alt" }); - ContextMenu.Instance.addItem({ description: "Options...", subitems: funcs, icon: "asterisk" }); + ContextMenu.Instance?.addItem({ description: "Options...", subitems: funcs, icon: "asterisk" }); } stopRecording = action(() => { @@ -193,7 +193,7 @@ export class AudioBox extends ViewBoxBaseComponent<FieldViewProps, AudioDocument const newDoc = Docs.Create.TextDocument("", { title: "", _chromeStatus: "disabled", x: NumCast(this.props.Document.x), y: NumCast(this.props.Document.y) + NumCast(this.props.Document._height) + 10, - _width: NumCast(this.props.Document._width), _height: 3 * NumCast(this.props.Document._height) + _width: NumCast(this.props.Document._width), _height: 2 * NumCast(this.props.Document._height) }); Doc.GetProto(newDoc).recordingSource = this.dataDoc; Doc.GetProto(newDoc).recordingStart = ComputedField.MakeFunction(`self.recordingSource["${this.props.fieldKey}-recordingStart"]`); @@ -228,7 +228,7 @@ export class AudioBox extends ViewBoxBaseComponent<FieldViewProps, AudioDocument {!this.path ? <div className="audiobox-buttons"> <div className="audiobox-dictation" onClick={this.onFile}> - <FontAwesomeIcon style={{ width: "30px", background: this.layoutDoc.playOnSelect ? "yellow" : "dimGray" }} icon="file-alt" size={this.props.PanelHeight() < 36 ? "1x" : "2x"} /> + <FontAwesomeIcon style={{ width: "30px", background: this.layoutDoc.playOnSelect ? "yellow" : "rgba(0,0,0,0)" }} icon="file-alt" size={this.props.PanelHeight() < 36 ? "1x" : "2x"} /> </div> <button className={`audiobox-record${interactive}`} style={{ backgroundColor: this.audioState === "recording" ? "red" : "black" }}> {this.audioState === "recording" ? "STOP" : "RECORD"} diff --git a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx index 404d69730..a3020f912 100644 --- a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx +++ b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx @@ -22,7 +22,7 @@ export interface CollectionFreeFormDocumentViewProps extends DocumentViewProps { zIndex?: number; highlight?: boolean; jitterRotation: number; - transition?: string; + dataTransition?: string; fitToBox?: boolean; replica: string; } @@ -60,10 +60,10 @@ export class CollectionFreeFormDocumentView extends DocComponent<CollectionFreeF const someView = Cast(this.props.Document.someView, Doc); const minimap = Cast(this.props.Document.minimap, Doc); if (someView instanceof Doc && minimap instanceof Doc) { - const x = (NumCast(someView._panX) - NumCast(someView._width) / 2 / NumCast(someView.scale) - (NumCast(minimap.fitX) - NumCast(minimap.fitW) / 2)) / NumCast(minimap.fitW) * NumCast(minimap._width) - NumCast(minimap._width) / 2; - const y = (NumCast(someView._panY) - NumCast(someView._height) / 2 / NumCast(someView.scale) - (NumCast(minimap.fitY) - NumCast(minimap.fitH) / 2)) / NumCast(minimap.fitH) * NumCast(minimap._height) - NumCast(minimap._height) / 2; - const w = NumCast(someView._width) / NumCast(someView.scale) / NumCast(minimap.fitW) * NumCast(minimap.width); - const h = NumCast(someView._height) / NumCast(someView.scale) / NumCast(minimap.fitH) * NumCast(minimap.height); + const x = (NumCast(someView._panX) - NumCast(someView._width) / 2 / NumCast(someView._viewScale) - (NumCast(minimap.fitX) - NumCast(minimap.fitW) / 2)) / NumCast(minimap.fitW) * NumCast(minimap._width) - NumCast(minimap._width) / 2; + const y = (NumCast(someView._panY) - NumCast(someView._height) / 2 / NumCast(someView._viewScale) - (NumCast(minimap.fitY) - NumCast(minimap.fitH) / 2)) / NumCast(minimap.fitH) * NumCast(minimap._height) - NumCast(minimap._height) / 2; + const w = NumCast(someView._width) / NumCast(someView._viewScale) / NumCast(minimap.fitW) * NumCast(minimap.width); + const h = NumCast(someView._height) / NumCast(someView._viewScale) / NumCast(minimap.fitH) * NumCast(minimap.height); return { x: x, y: y, width: w, height: h }; } } @@ -81,9 +81,15 @@ export class CollectionFreeFormDocumentView extends DocComponent<CollectionFreeF public static setValues(time: number, d: Doc, x?: number, y?: number, opacity?: number) { const timecode = Math.round(time); - Cast(d["x-indexed"], listSpec("number"), [])[timecode] = x as any as number; - Cast(d["y-indexed"], listSpec("number"), [])[timecode] = y as any as number; - Cast(d["opacity-indexed"], listSpec("number"), null)[timecode] = opacity as any as number; + const xindexed = Cast(d["x-indexed"], listSpec("number"), []).slice(); + const yindexed = Cast(d["y-indexed"], listSpec("number"), []).slice(); + const oindexed = Cast(d["opacity-indexed"], listSpec("number"), []).slice(); + xindexed[timecode] = x as any as number; + yindexed[timecode] = y as any as number; + oindexed[timecode] = opacity as any as number; + d["x-indexed"] = new List<number>(xindexed); + d["y-indexed"] = new List<number>(yindexed); + d["opacity-indexed"] = new List<number>(oindexed); } public static updateKeyframe(docs: Doc[], time: number) { const timecode = Math.round(time); @@ -94,14 +100,14 @@ export class CollectionFreeFormDocumentView extends DocComponent<CollectionFreeF xindexed?.length <= timecode + 1 && xindexed.push(undefined as any as number); yindexed?.length <= timecode + 1 && yindexed.push(undefined as any as number); opacityindexed?.length <= timecode + 1 && opacityindexed.push(undefined as any as number); - doc.transition = "all 1s"; + doc.dataTransition = "all 1s"; }); - setTimeout(() => docs.forEach(doc => doc.transition = "inherit"), 1010); + setTimeout(() => docs.forEach(doc => doc.dataTransition = "inherit"), 1010); } public static gotoKeyframe(docs: Doc[]) { - docs.forEach(doc => doc.transition = "all 1s"); - setTimeout(() => docs.forEach(doc => doc.transition = "inherit"), 1010); + docs.forEach(doc => doc.dataTransition = "all 1s"); + setTimeout(() => docs.forEach(doc => doc.dataTransition = "inherit"), 1010); } public static setupKeyframes(docs: Doc[], timecode: number, progressivize: boolean = false) { @@ -119,7 +125,7 @@ export class CollectionFreeFormDocumentView extends DocComponent<CollectionFreeF doc.x = ComputedField.MakeInterpolated("x", "activeFrame"); doc.y = ComputedField.MakeInterpolated("y", "activeFrame"); doc.opacity = ComputedField.MakeInterpolated("opacity", "activeFrame"); - doc.transition = "inherit"; + doc.dataTransition = "inherit"; }); } @@ -150,7 +156,7 @@ export class CollectionFreeFormDocumentView extends DocComponent<CollectionFreeF borderRadius: StrCast(Doc.Layout(this.layoutDoc).borderRounding), outline: this.Highlight ? "orange solid 2px" : "", transform: this.transform, - transition: this.props.transition ? this.props.transition : this.dataProvider ? this.dataProvider.transition : StrCast(this.layoutDoc.transition), + transition: this.props.dataTransition ? this.props.dataTransition : this.dataProvider ? this.dataProvider.transition : StrCast(this.layoutDoc.dataTransition), width: this.props.Document.isInkMask ? 5000 : this.width, height: this.props.Document.isInkMask ? 5000 : this.height, zIndex: this.ZInd, diff --git a/src/client/views/nodes/ColorBox.tsx b/src/client/views/nodes/ColorBox.tsx index d6d9a8cfd..b3a9b6fee 100644 --- a/src/client/views/nodes/ColorBox.tsx +++ b/src/client/views/nodes/ColorBox.tsx @@ -39,7 +39,7 @@ export class ColorBox extends ViewBoxBaseComponent<FieldViewProps, ColorDocument if (view.props.LayoutTemplate?.() || view.props.LayoutTemplateString) { // this situation typically occurs when you have a link dot targetDoc.backgroundColor = Doc.UserDoc().backgroundColor; // bcz: don't know how to change the color of an inline template... } - else if (StrCast(Doc.Layout(view.props.Document).layout).includes("FormattedTextBox") && FormattedTextBox.HadSelection) { + else if (StrCast(Doc.Layout(view.props.Document).layout).includes("FormattedTextBox") && window.getSelection()?.toString() !== "") { Doc.Layout(view.props.Document)[Doc.LayoutFieldKey(view.props.Document) + "-color"] = Doc.UserDoc().backgroundColor; } else { Doc.Layout(view.props.Document)._backgroundColor = Doc.UserDoc().backgroundColor; // '_backgroundColor' is template specific. 'backgroundColor' would apply to all templates, but has no UI at the moment @@ -71,4 +71,4 @@ export class ColorBox extends ViewBoxBaseComponent<FieldViewProps, ColorDocument </div> </div>; } -}
\ No newline at end of file +} diff --git a/src/client/views/nodes/ComparisonBox.scss b/src/client/views/nodes/ComparisonBox.scss index 810a824cf..acf6b1636 100644 --- a/src/client/views/nodes/ComparisonBox.scss +++ b/src/client/views/nodes/ComparisonBox.scss @@ -3,7 +3,7 @@ border-radius: inherit; width: 100%; height: 100%; - position: absolute; + position: relative; z-index: 0; pointer-events: none; diff --git a/src/client/views/nodes/DocumentLinksButton.scss b/src/client/views/nodes/DocumentLinksButton.scss index 484f8c469..b58603978 100644 --- a/src/client/views/nodes/DocumentLinksButton.scss +++ b/src/client/views/nodes/DocumentLinksButton.scss @@ -23,7 +23,7 @@ &:hover { background: deepskyblue; transform: scale(1.05); - cursor: default; + cursor: grab; } } .documentLinksButton { diff --git a/src/client/views/nodes/DocumentLinksButton.tsx b/src/client/views/nodes/DocumentLinksButton.tsx index f35b48ce4..bfd860f65 100644 --- a/src/client/views/nodes/DocumentLinksButton.tsx +++ b/src/client/views/nodes/DocumentLinksButton.tsx @@ -10,6 +10,7 @@ import React = require("react"); import { DocUtils } from "../../documents/Documents"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { LinkDocPreview } from "./LinkDocPreview"; +import { LinkCreatedBox } from "./LinkCreatedBox"; const higflyout = require("@hig/flyout"); export const { anchorPoints } = higflyout; export const Flyout = higflyout.default; @@ -18,11 +19,14 @@ interface DocumentLinksButtonProps { View: DocumentView; Offset?: number[]; AlwaysOn?: boolean; + InMenu?: boolean; } @observer export class DocumentLinksButton extends React.Component<DocumentLinksButtonProps, {}> { private _linkButton = React.createRef<HTMLDivElement>(); + @observable public static StartLink: DocumentView | undefined; + @action onLinkButtonMoved = (e: PointerEvent) => { if (this._linkButton.current !== null) { @@ -50,30 +54,73 @@ export class DocumentLinksButton extends React.Component<DocumentLinksButtonProp return false; } - @observable static StartLink: DocumentView | undefined; onLinkButtonDown = (e: React.PointerEvent): void => { setupMoveUpEvents(this, e, this.onLinkButtonMoved, emptyFunction, action((e, doubleTap) => { - if (doubleTap) { + if (doubleTap && this.props.InMenu) { + //action(() => Doc.BrushDoc(this.props.View.Document)); DocumentLinksButton.StartLink = this.props.View; - } else { + } else if (!!!this.props.InMenu) { DocumentLinksButton.EditLink = this.props.View; DocumentLinksButton.EditLinkLoc = [e.clientX + 10, e.clientY]; } })); } + + @action + onLinkClick = (e: React.MouseEvent): void => { + if (this.props.InMenu) { + DocumentLinksButton.StartLink = this.props.View; + //action(() => Doc.BrushDoc(this.props.View.Document)); + } else if (!!!this.props.InMenu) { + DocumentLinksButton.EditLink = this.props.View; + DocumentLinksButton.EditLinkLoc = [e.clientX + 10, e.clientY]; + } + } + + @action completeLink = (e: React.PointerEvent): void => { setupMoveUpEvents(this, e, returnFalse, emptyFunction, action((e, doubleTap) => { if (doubleTap) { if (DocumentLinksButton.StartLink === this.props.View) { DocumentLinksButton.StartLink = undefined; + // action((e: React.PointerEvent<HTMLDivElement>) => { + // Doc.UnBrushDoc(this.props.View.Document); + // }); } else { DocumentLinksButton.StartLink && DocumentLinksButton.StartLink !== this.props.View && DocUtils.MakeLink({ doc: DocumentLinksButton.StartLink.props.Document }, { doc: this.props.View.props.Document }, "long drag"); + + runInAction(() => { + LinkCreatedBox.popupX = e.screenX; + LinkCreatedBox.popupY = e.screenY - 120; + LinkCreatedBox.linkCreated = true; + setTimeout(action(() => { LinkCreatedBox.linkCreated = false; }), 2500); + }); } } })); } + @action + finishLinkClick = (e: React.MouseEvent) => { + if (DocumentLinksButton.StartLink === this.props.View) { + DocumentLinksButton.StartLink = undefined; + // action((e: React.PointerEvent<HTMLDivElement>) => { + // Doc.UnBrushDoc(this.props.View.Document); + // }); + } else { + DocumentLinksButton.StartLink && DocumentLinksButton.StartLink !== this.props.View && + DocUtils.MakeLink({ doc: DocumentLinksButton.StartLink.props.Document }, { doc: this.props.View.props.Document }, "long drag"); + + runInAction(() => { + LinkCreatedBox.popupX = e.screenX; + LinkCreatedBox.popupY = e.screenY - 120; + LinkCreatedBox.linkCreated = true; + setTimeout(action(() => { LinkCreatedBox.linkCreated = false; }), 2500); + }); + } + } + @observable public static EditLink: DocumentView | undefined; public static EditLinkLoc: number[] = [0, 0]; @@ -82,23 +129,30 @@ export class DocumentLinksButton extends React.Component<DocumentLinksButtonProp get linkButton() { const links = DocListCast(this.props.View.props.Document.links); return (!links.length || links[0].hidden) && !this.props.AlwaysOn ? (null) : - <div title="Drag(create link) Tap(view links)" ref={this._linkButton} style={{ position: "absolute", left: this.props.Offset?.[0] }}> - <div className={"documentLinksButton"} style={{ backgroundColor: DocumentLinksButton.StartLink ? "transparent" : "" }} - onPointerDown={this.onLinkButtonDown} - onPointerLeave={action(() => LinkDocPreview.LinkInfo = undefined)} - onPointerEnter={action(e => LinkDocPreview.LinkInfo = { - addDocTab: this.props.View.props.addDocTab, - linkSrc: this.props.View.props.Document, - linkDoc: links[0], - Location: [e.clientX, e.clientY + 20] - })} > - {links.length ? links.length : <FontAwesomeIcon className="documentdecorations-icon" icon="link" size="sm" />} + <div title="Drag(create link) Tap(view links)" ref={this._linkButton} style={{ minWidth: 20, minHeight: 20, position: "absolute", left: this.props.Offset?.[0] }}> + <div className={"documentLinksButton"} style={{ + backgroundColor: DocumentLinksButton.StartLink ? "transparent" : "", + width: this.props.InMenu ? "20px" : "30px", height: this.props.InMenu ? "20px" : "30px", fontWeight: "bold" + }} + onPointerDown={this.onLinkButtonDown} onClick={this.onLinkClick} + // onPointerLeave={action(() => LinkDocPreview.LinkInfo = undefined)} + // onPointerEnter={action(e => links.length && (LinkDocPreview.LinkInfo = { + // addDocTab: this.props.View.props.addDocTab, + // linkSrc: this.props.View.props.Document, + // linkDoc: links[0], + // Location: [e.clientX, e.clientY + 20] + // }))} + > + {links.length && !!!this.props.InMenu ? links.length : <FontAwesomeIcon className="documentdecorations-icon" icon="link" size="sm" />} </div> - {DocumentLinksButton.StartLink && DocumentLinksButton.StartLink !== this.props.View ? <div className={"documentLinksButton-endLink"} onPointerDown={this.completeLink} /> : (null)} - {DocumentLinksButton.StartLink === this.props.View ? <div className={"documentLinksButton-startLink"} /> : (null)} + {DocumentLinksButton.StartLink && DocumentLinksButton.StartLink !== this.props.View ? <div className={"documentLinksButton-endLink"} + style={{ width: this.props.InMenu ? "20px" : "30px", height: this.props.InMenu ? "20px" : "30px" }} + onPointerDown={this.completeLink} onClick={e => this.finishLinkClick(e)} /> : (null)} + {DocumentLinksButton.StartLink === this.props.View ? <div className={"documentLinksButton-startLink"} + style={{ width: this.props.InMenu ? "20px" : "30px", height: this.props.InMenu ? "20px" : "30px" }} /> : (null)} </div>; } render() { return this.linkButton; } -}
\ No newline at end of file +} diff --git a/src/client/views/nodes/DocumentView.scss b/src/client/views/nodes/DocumentView.scss index b7726f7ba..b978f6245 100644 --- a/src/client/views/nodes/DocumentView.scss +++ b/src/client/views/nodes/DocumentView.scss @@ -42,6 +42,17 @@ width:10px !important; } } + .documentView-treeView { + max-height: 1.5em; + text-overflow: ellipsis; + display: inline-block; + white-space: pre; + width: 100%; + overflow: hidden; + > .documentView-node { + position: absolute; + } + } .documentView-lock { width: 20; diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 8f139e39e..b38db9a1e 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -29,7 +29,6 @@ import { SelectionManager } from "../../util/SelectionManager"; import SharingManager from '../../util/SharingManager'; import { Transform } from "../../util/Transform"; import { undoBatch, UndoManager } from "../../util/UndoManager"; -import { CollectionDockingView } from "../collections/CollectionDockingView"; import { CollectionView, CollectionViewType } from '../collections/CollectionView'; import { ContextMenu } from "../ContextMenu"; import { ContextMenuProps } from '../ContextMenuItem'; @@ -42,6 +41,8 @@ import { LinkAnchorBox } from './LinkAnchorBox'; import { RadialMenu } from './RadialMenu'; import React = require("react"); import { DocumentLinksButton } from './DocumentLinksButton'; +import { MobileInterface } from '../../../mobile/MobileInterface'; +import { LinkCreatedBox } from './LinkCreatedBox'; library.add(fa.faEdit, fa.faTrash, fa.faShare, fa.faDownload, fa.faExpandArrowsAlt, fa.faCompressArrowsAlt, fa.faLayerGroup, fa.faExternalLinkAlt, fa.faAlignCenter, fa.faCaretSquareRight, fa.faSquare, fa.faConciergeBell, fa.faWindowRestore, fa.faFolder, fa.faMapPin, fa.faLink, fa.faFingerprint, fa.faCrosshairs, fa.faDesktop, fa.faUnlock, fa.faLock, fa.faLaptopCode, fa.faMale, @@ -69,7 +70,7 @@ export interface DocumentViewProps { onDoubleClick?: ScriptField; onPointerDown?: ScriptField; onPointerUp?: ScriptField; - treeViewId?: string; + treeViewDoc?: Doc; dropAction?: dropActionType; dragDivName?: string; nudge?: (x: number, y: number) => void; @@ -116,6 +117,7 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu protected multiTouchDisposer?: InteractionUtils.MultiTouchEventDisposer; private holdDisposer?: InteractionUtils.MultiTouchEventDisposer; + public get title() { return this.props.Document.title; } public get displayName() { return "DocumentView(" + this.props.Document.title + ")"; } // this makes mobx trace() statements more descriptive public get ContentDiv() { return this._mainCont.current; } get active() { return SelectionManager.IsSelected(this, true) || this.props.parentActive(true); } @@ -123,7 +125,7 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu @computed get freezeDimensions() { return this.props.FreezeDimensions; } @computed get nativeWidth() { return NumCast(this.layoutDoc._nativeWidth, this.props.NativeWidth() || (this.freezeDimensions ? this.layoutDoc[WidthSym]() : 0)); } @computed get nativeHeight() { return NumCast(this.layoutDoc._nativeHeight, this.props.NativeHeight() || (this.freezeDimensions ? this.layoutDoc[HeightSym]() : 0)); } - @computed get onClickHandler() { return this.props.onClick || Cast(this.layoutDoc.onClick, ScriptField, null); } + @computed get onClickHandler() { return this.props.onClick || Cast(this.Document.onClick, ScriptField, Cast(this.layoutDoc.onClick, ScriptField, null)); } @computed get onDoubleClickHandler() { return this.props.onDoubleClick || Cast(this.layoutDoc.onDoubleClick, ScriptField, null) || this.Document.onDoubleClick; } @computed get onPointerDownHandler() { return this.props.onPointerDown ? this.props.onPointerDown : this.Document.onPointerDown; } @computed get onPointerUpHandler() { return this.props.onPointerUp ? this.props.onPointerUp : this.Document.onPointerUp; } @@ -181,10 +183,11 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu const pt = me.touchEvent.touches[me.touchEvent.touches.length - 1]; RadialMenu.Instance.openMenu(pt.pageX - 15, pt.pageY - 15); - RadialMenu.Instance.addItem({ description: "Open Fields", event: () => this.props.addDocTab(Docs.Create.KVPDocument(this.props.Document, { _width: 300, _height: 300 }), "onRight"), icon: "map-pin", selected: -1 }); - RadialMenu.Instance.addItem({ description: "Delete this document", event: () => { this.props.ContainingCollectionView?.removeDocument(this.props.Document), RadialMenu.Instance.closeMenu(); }, icon: "layer-group", selected: -1 }); - RadialMenu.Instance.addItem({ description: "Open in a new tab", event: () => this.props.addDocTab(this.props.Document, "onRight"), icon: "trash", selected: -1 }); - RadialMenu.Instance.addItem({ description: "Pin to Presentation", event: () => this.props.pinToPres(this.props.Document), icon: "folder", selected: -1 }); + // RadialMenu.Instance.addItem({ description: "Open Fields", event: () => this.props.addDocTab(Docs.Create.KVPDocument(this.props.Document, { _width: 300, _height: 300 }), "onRight"), icon: "map-pin", selected: -1 }); + RadialMenu.Instance.addItem({ description: "Delete", event: () => { this.props.ContainingCollectionView?.removeDocument(this.props.Document), RadialMenu.Instance.closeMenu(); }, icon: "external-link-square-alt", selected: -1 }); + // RadialMenu.Instance.addItem({ description: "Open in a new tab", event: () => this.props.addDocTab(this.props.Document, "onRight"), icon: "trash", selected: -1 }); + RadialMenu.Instance.addItem({ description: "Pin", event: () => this.props.pinToPres(this.props.Document), icon: "map-pin", selected: -1 }); + RadialMenu.Instance.addItem({ description: "Open", event: () => MobileInterface.Instance.handleClick(this.props.Document), icon: "trash", selected: -1 }); SelectionManager.DeselectAll(); } @@ -237,7 +240,7 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu dragData.removeDocument = this.props.removeDocument; dragData.moveDocument = this.props.moveDocument;// this.layoutDoc.onDragStart ? undefined : this.props.moveDocument; dragData.dragDivName = this.props.dragDivName; - dragData.treeViewId = this.props.treeViewId; + dragData.treeViewDoc = this.props.treeViewDoc; DragManager.StartDocumentDrag([this._mainCont.current], dragData, x, y, { hideSource: !dropAction && !this.layoutDoc.onDragStart }); } } @@ -345,12 +348,12 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu // depending on the followLinkLocation property of the source (or the link itself as a fallback); followLinkClick = async (altKey: boolean, ctrlKey: boolean, shiftKey: boolean) => { const batch = UndoManager.StartBatch("follow link click"); - // open up target if it's not already in view ... + // open up target if it's not already in view ... const createViewFunc = (doc: Doc, followLoc: string, finished: Opt<() => void>) => { const targetFocusAfterDocFocus = () => { const where = StrCast(this.Document.followLinkLocation) || followLoc; const hackToCallFinishAfterFocus = () => { - finished && setTimeout(finished, 0); // finished() needs to be called right after hackToCallFinishAfterFocus(), but there's no callback for that so we use the hacky timeout. + finished && setTimeout(finished, 0); // finished() needs to be called right after hackToCallFinishAfterFocus(), but there's no callback for that so we use the hacky timeout. return false; // we must return false here so that the zoom to the document is not reversed. If it weren't for needing to call finished(), we wouldn't need this function at all since not having it is equivalent to returning false }; this.props.addDocTab(doc, where) && this.props.focus(doc, BoolCast(this.Document.followLinkZoom, true), undefined, hackToCallFinishAfterFocus); // add the target and focus on it. @@ -374,7 +377,7 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu this._downX = touch.clientX; this._downY = touch.clientY; if (!e.nativeEvent.cancelBubble) { - if ((this.active || this.layoutDoc.onDragStart || this.layoutDoc.onClick) && !e.ctrlKey && !this.layoutDoc.lockedPosition && !this.layoutDoc.inOverlay) e.stopPropagation(); + if ((this.active || this.layoutDoc.onDragStart || this.onClickHandler) && !e.ctrlKey && !this.layoutDoc.lockedPosition && !this.layoutDoc.inOverlay) e.stopPropagation(); this.removeMoveListeners(); this.addMoveListeners(); this.removeEndListeners(); @@ -389,11 +392,11 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu if (e.cancelBubble && this.active) { this.removeMoveListeners(); } - else if (!e.cancelBubble && (SelectionManager.IsSelected(this, true) || this.props.parentActive(true) || this.layoutDoc.onDragStart || this.layoutDoc.onClick) && !this.layoutDoc.lockedPosition && !this.layoutDoc.inOverlay) { + else if (!e.cancelBubble && (SelectionManager.IsSelected(this, true) || this.props.parentActive(true) || this.layoutDoc.onDragStart || this.onClickHandler) && !this.layoutDoc.lockedPosition && !this.layoutDoc.inOverlay) { const touch = me.touchEvent.changedTouches.item(0); if (touch && (Math.abs(this._downX - touch.clientX) > 3 || Math.abs(this._downY - touch.clientY) > 3)) { - if (!e.altKey && (!this.topMost || this.layoutDoc.onDragStart || this.layoutDoc.onClick)) { + if (!e.altKey && (!this.topMost || this.layoutDoc.onDragStart || this.onClickHandler)) { this.cleanUpInteractions(); this.startDragging(this._downX, this._downY, this.Document.dropAction ? this.Document.dropAction as any : e.ctrlKey || e.altKey ? "alias" : undefined); } @@ -582,12 +585,12 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu @undoBatch toggleLinkButtonBehavior = (): void => { - if (this.Document.isLinkButton || this.layoutDoc.onClick || this.Document.ignoreClick) { + if (this.Document.isLinkButton || this.onClickHandler || this.Document.ignoreClick) { this.Document.isLinkButton = false; const first = DocListCast(this.Document.links).find(d => d instanceof Doc); first && (first.hidden = false); this.Document.ignoreClick = false; - this.layoutDoc.onClick = undefined; + this.Document.onClick = this.layoutDoc.onClick = undefined; } else { this.Document.isLinkButton = true; const first = DocListCast(this.Document.links).find(d => d instanceof Doc); @@ -639,12 +642,27 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu e.stopPropagation(); de.complete.annoDragData.linkedToDoc = true; + runInAction(() => { + LinkCreatedBox.popupX = de.x; + LinkCreatedBox.popupY = de.y; + LinkCreatedBox.linkCreated = true; + setTimeout(action(() => { LinkCreatedBox.linkCreated = false; }), 2500); + }); + DocUtils.MakeLink({ doc: de.complete.annoDragData.annotationDocument }, { doc: this.props.Document }, "link"); } if (de.complete.linkDragData) { e.stopPropagation(); // const docs = await SearchUtil.Search(`data_l:"${destDoc[Id]}"`, true); // const views = docs.map(d => DocumentManager.Instance.getDocumentView(d)).filter(d => d).map(d => d as DocumentView); + + runInAction(() => { + LinkCreatedBox.popupX = de.x; + LinkCreatedBox.popupY = de.y; + LinkCreatedBox.linkCreated = true; + setTimeout(action(() => { LinkCreatedBox.linkCreated = false; }), 2500); + }); + de.complete.linkDragData.linkSourceDocument !== this.props.Document && (de.complete.linkDragData.linkDocument = DocUtils.MakeLink({ doc: de.complete.linkDragData.linkSourceDocument }, { doc: this.props.Document }, `link`)); // TODODO this is where in text links get passed @@ -689,7 +707,7 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu @undoBatch @action - setAcl = (acl: "readOnly" | "addOnly" | "ownerOnly") => { + setAcl = (acl: "readOnly" | "addOnly" | "ownerOnly" | "write") => { 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; @@ -699,7 +717,7 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu } @undoBatch @action - testAcl = (acl: "readOnly" | "addOnly" | "ownerOnly") => { + testAcl = (acl: "readOnly" | "addOnly" | "ownerOnly" | "write") => { 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 => { @@ -724,17 +742,18 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu return; } e.persist(); - e?.stopPropagation(); + e.stopPropagation(); - if (Math.abs(this._downX - e.clientX) > 3 || Math.abs(this._downY - e.clientY) > 3 || - e.isDefaultPrevented()) { - e.preventDefault(); + if (Math.abs(this._downX - e?.clientX) > 3 || Math.abs(this._downY - e?.clientY) > 3 || + e?.isDefaultPrevented()) { + e?.preventDefault(); return; } e.preventDefault(); } const cm = ContextMenu.Instance; + if (!cm) return; const customScripts = Cast(this.props.Document.contextMenuScripts, listSpec(ScriptField), []); Cast(this.props.Document.contextMenuLabels, listSpec("string"), []).forEach((label, i) => @@ -742,7 +761,7 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu this.props.contextMenuItems?.().forEach(item => cm.addItem({ description: item.label, event: () => item.script.script.run({ this: this.layoutDoc, self: this.rootDoc }), icon: "sticky-note" })); - let options = cm.findByDescription("Options..."); + const options = cm.findByDescription("Options..."); const optionItems: ContextMenuProps[] = options && "subitems" in options ? options.subitems : []; const templateDoc = Cast(this.props.Document[StrCast(this.props.Document.layoutKey)], Doc, null); templateDoc && optionItems.push({ description: "Open Template ", event: () => this.props.addDocTab(templateDoc, "onRight"), icon: "eye" }); @@ -752,11 +771,11 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu const existingOnClick = cm.findByDescription("OnClick..."); const onClicks: ContextMenuProps[] = existingOnClick && "subitems" in existingOnClick ? existingOnClick.subitems : []; onClicks.push({ description: "Enter Portal", event: this.makeIntoPortal, icon: "window-restore" }); - onClicks.push({ description: "Toggle Detail", event: () => this.layoutDoc.onClick = ScriptField.MakeScript(`toggleDetail(self, "${this.Document.layoutKey}")`), icon: "window-restore" }); + onClicks.push({ description: "Toggle Detail", event: () => this.Document.onClick = ScriptField.MakeScript(`toggleDetail(self, "${this.Document.layoutKey}")`), icon: "window-restore" }); onClicks.push({ description: this.Document.ignoreClick ? "Select" : "Do Nothing", event: () => this.Document.ignoreClick = !this.Document.ignoreClick, icon: this.Document.ignoreClick ? "unlock" : "lock" }); onClicks.push({ description: this.Document.isLinkButton ? "Remove Follow Behavior" : "Follow Link in Place", event: this.toggleFollowInPlace, icon: "concierge-bell" }); onClicks.push({ description: this.Document.isLinkButton ? "Remove Follow Behavior" : "Follow Link on Right", event: this.toggleFollowOnRight, icon: "concierge-bell" }); - onClicks.push({ description: this.Document.isLinkButton || this.layoutDoc.onClick ? "Remove Click Behavior" : "Follow Link", event: this.toggleLinkButtonBehavior, icon: "concierge-bell" }); + onClicks.push({ description: this.Document.isLinkButton || this.onClickHandler ? "Remove Click Behavior" : "Follow Link", event: this.toggleLinkButtonBehavior, icon: "concierge-bell" }); onClicks.push({ description: "Edit onClick Script", event: () => UndoManager.RunInBatch(() => DocUtils.makeCustomViewClicked(this.props.Document, undefined, "onClick"), "edit onClick"), icon: "edit" }); !existingOnClick && cm.addItem({ description: "OnClick...", subitems: onClicks, icon: "hand-point-right" }); @@ -811,6 +830,7 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu aclItems.push({ description: "Make Add Only", event: () => this.setAcl("addOnly"), icon: "concierge-bell" }); aclItems.push({ description: "Make Read Only", event: () => this.setAcl("readOnly"), icon: "concierge-bell" }); aclItems.push({ description: "Make Private", event: () => this.setAcl("ownerOnly"), icon: "concierge-bell" }); + aclItems.push({ description: "Make Editable", event: () => this.setAcl("write"), icon: "concierge-bell" }); aclItems.push({ description: "Test Private", event: () => this.testAcl("ownerOnly"), icon: "concierge-bell" }); aclItems.push({ description: "Test Readonly", event: () => this.testAcl("readOnly"), icon: "concierge-bell" }); !existingAcls && cm.addItem({ description: "Privacy...", subitems: aclItems, icon: "question" }); @@ -874,7 +894,7 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu // DocumentViews should stop propagation of this event e.stopPropagation(); } - ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15); + cm.displayMenu(e.pageX - 15, e.pageY - 15); !SelectionManager.IsSelected(this, true) && SelectionManager.SelectDoc(this, false); }); const path = this.props.LibraryPath.reduce((p: string, d: Doc) => p + "/" + (Doc.AreProtosEqual(d, (Doc.UserDoc()["tabs-button-library"] as Doc).sourcePanel as Doc) ? "" : d.title), ""); @@ -942,7 +962,7 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu recommendations.documentIconHeight = 150; recommendations.sourceDoc = this.props.Document; recommendations.sourceDocContext = this.props.ContainingCollectionView!.props.Document; - CollectionDockingView.AddRightSplit(recommendations, undefined); + this.props.addDocTab(recommendations, "onRight"); // RecommendationsBox.Instance.displayRecommendations(e.pageX + 100, e.pageY); } @@ -974,13 +994,13 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu body.href = urls[i]; bodies.push(body); } - CollectionDockingView.AddRightSplit(Docs.Create.SchemaDocument(headers, bodies, { title: `Showing External Recommendations for "${StrCast(doc.title)}"` }), undefined); + this.props.addDocTab(Docs.Create.SchemaDocument(headers, bodies, { title: `Showing External Recommendations for "${StrCast(doc.title)}"` }), "onRight"); this._showKPQuery = true; this._queries = kps.toString(); } // does Document set a layout prop - // does Document set a layout prop + // does Document set a layout prop setsLayoutProp = (prop: string) => this.props.Document[prop] !== this.props.Document["default" + prop[0].toUpperCase() + prop.slice(1)] && this.props.Document["default" + prop[0].toUpperCase() + prop.slice(1)]; // get the a layout prop by first choosing the prop from Document, then falling back to the layout doc otherwise. getLayoutPropStr = (prop: string) => StrCast(this.setsLayoutProp(prop) ? this.props.Document[prop] : this.layoutDoc[prop]); @@ -1071,30 +1091,34 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu anchorPanelHeight = () => this.props.PanelHeight() || 1; @computed get anchors() { TraceMobx(); - return this.props.forcedBackgroundColor?.(this.Document) === "transparent" || this.layoutDoc.presBox || this.props.dontRegisterView ? (null) : DocListCast(this.Document.links).filter(d => !d.hidden && this.isNonTemporalLink).map((d, i) => - <DocumentView {...this.props} key={i + 1} - Document={d} - ContainingCollectionView={this.props.ContainingCollectionView} - ContainingCollectionDoc={this.props.Document} // bcz: hack this.props.Document is not a collection Need a better prop for passing the containing document to the LinkAnchorBox - PanelWidth={this.anchorPanelWidth} - PanelHeight={this.anchorPanelHeight} - ContentScaling={returnOne} - dontRegisterView={false} - forcedBackgroundColor={returnTransparent} - removeDocument={this.hideLinkAnchor} - pointerEvents={false} - LayoutTemplate={undefined} - LayoutTemplateString={LinkAnchorBox.LayoutString(`anchor${Doc.LinkEndpoint(d, this.props.Document)}`)} - />); + return (this.props.treeViewDoc && this.props.LayoutTemplateString) || // render nothing for: tree view anchor dots + this.layoutDoc.presBox || // presentationbox nodes + this.props.dontRegisterView ? (null) : // view that are not registered + DocListCast(this.Document.links).filter(d => !d.hidden && this.isNonTemporalLink).map((d, i) => + <DocumentView {...this.props} key={i + 1} + Document={d} + ContainingCollectionView={this.props.ContainingCollectionView} + ContainingCollectionDoc={this.props.Document} // bcz: hack this.props.Document is not a collection Need a better prop for passing the containing document to the LinkAnchorBox + PanelWidth={this.anchorPanelWidth} + PanelHeight={this.anchorPanelHeight} + ContentScaling={returnOne} + dontRegisterView={false} + forcedBackgroundColor={returnTransparent} + removeDocument={this.hideLinkAnchor} + pointerEvents={false} + LayoutTemplate={undefined} + LayoutTemplateString={LinkAnchorBox.LayoutString(`anchor${Doc.LinkEndpoint(d, this.props.Document)}`)} + />); } @computed get innards() { TraceMobx(); - if (!this.props.PanelWidth()) { // this happens when the document is a tree view label - return <div className="documentView-linkAnchorBoxAnchor" > + if (this.props.treeViewDoc && !this.props.LayoutTemplateString) { // this happens when the document is a tree view label (but not an anchor dot) + return <div className="documentView-treeView" style={{ maxWidth: this.props.PanelWidth() || undefined }}> {StrCast(this.props.Document.title)} {this.anchors} </div>; } + const showTitle = StrCast(this.layoutDoc._showTitle); const showTitleHover = StrCast(this.layoutDoc._showTitleHover); const showCaption = StrCast(this.layoutDoc._showCaption); @@ -1156,7 +1180,7 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu renderLock() { return (this.Document.isBackground !== undefined || this.isSelected(false)) && ((this.Document.type === DocumentType.COL && this.Document._viewType !== CollectionViewType.Pile) || this.Document.type === DocumentType.IMG) && - this.props.renderDepth > 0 && this.props.PanelWidth() > 0 ? + this.props.renderDepth > 0 && !this.props.treeViewDoc ? <div className="documentView-lock" onClick={() => this.toggleBackground(true)}> <FontAwesomeIcon icon={this.Document.isBackground ? "unlock" : "lock"} style={{ color: this.Document.isBackground ? "red" : undefined }} size="lg" /> </div> @@ -1164,8 +1188,9 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu } render() { - if (this.props.Document[AclSym] && this.props.Document[AclSym] === AclPrivate) return (null); if (!(this.props.Document instanceof Doc)) return (null); + if (this.props.Document[AclSym] && this.props.Document[AclSym] === AclPrivate) return (null); + if (this.props.Document.hidden) return (null); const backgroundColor = Doc.UserDoc().renderStyle === "comic" ? undefined : this.props.forcedBackgroundColor?.(this.Document) || StrCast(this.layoutDoc._backgroundColor) || StrCast(this.layoutDoc.backgroundColor) || StrCast(this.Document.backgroundColor) || this.props.backgroundColor?.(this.Document); const opacity = Cast(this.layoutDoc._opacity, "number", Cast(this.layoutDoc.opacity, "number", Cast(this.Document.opacity, "number", null))); const finalOpacity = this.props.opacity ? this.props.opacity() : opacity; @@ -1184,7 +1209,7 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu id={this.props.Document[Id]} ref={this._mainCont} onKeyDown={this.onKeyDown} onContextMenu={this.onContextMenu} onPointerDown={this.onPointerDown} onClick={this.onClick} - onPointerEnter={action(() => Doc.BrushDoc(this.props.Document))} + onPointerEnter={action(() => { Doc.BrushDoc(this.props.Document); })} onPointerLeave={action((e: React.PointerEvent<HTMLDivElement>) => { let entered = false; const target = document.elementFromPoint(e.nativeEvent.x, e.nativeEvent.y); @@ -1193,12 +1218,15 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu entered = true; } } + // if (this.props.Document !== DocumentLinksButton.StartLink?.Document) { !entered && Doc.UnBrushDoc(this.props.Document); + //} + })} style={{ transformOrigin: this._animateScalingTo ? "center center" : undefined, transform: this._animateScalingTo ? `scale(${this._animateScalingTo})` : undefined, - transition: !this._animateScalingTo ? StrCast(this.Document.transition) : this._animateScalingTo < 1 ? "transform 0.5s ease-in" : "transform 0.5s ease-out", + transition: !this._animateScalingTo ? StrCast(this.Document.dataTransition) : this._animateScalingTo < 1 ? "transform 0.5s ease-in" : "transform 0.5s ease-out", pointerEvents: this.ignorePointerEvents ? "none" : undefined, color: StrCast(this.layoutDoc.color, "inherit"), outline: highlighting && !borderRounding ? `${highlightColors[fullDegree]} ${highlightStyles[fullDegree]} ${localScale}px` : "solid 0px", @@ -1227,4 +1255,4 @@ Scripting.addGlobal(function toggleDetail(doc: any, layoutKey: string, otherKey: const dv = DocumentManager.Instance.getDocumentView(doc); if (dv?.props.Document.layoutKey === layoutKey) dv?.switchViews(otherKey !== "layout", otherKey.replace("layout_", "")); else dv?.switchViews(true, layoutKey.replace("layout_", "")); -});
\ No newline at end of file +}); diff --git a/src/client/views/nodes/FontIconBox.tsx b/src/client/views/nodes/FontIconBox.tsx index cf0b16c7c..5e8dd2497 100644 --- a/src/client/views/nodes/FontIconBox.tsx +++ b/src/client/views/nodes/FontIconBox.tsx @@ -5,7 +5,7 @@ import { createSchema, makeInterface } from '../../../fields/Schema'; import { DocComponent } from '../DocComponent'; import './FontIconBox.scss'; import { FieldView, FieldViewProps } from './FieldView'; -import { StrCast, Cast } from '../../../fields/Types'; +import { StrCast, Cast, NumCast } from '../../../fields/Types'; import { Utils } from "../../../Utils"; import { runInAction, observable, reaction, IReactionDisposer } from 'mobx'; import { Doc } from '../../../fields/Doc'; @@ -59,13 +59,14 @@ export class FontIconBox extends DocComponent<FieldViewProps, FontIconDocument>( render() { const referenceDoc = (this.layoutDoc.dragFactory instanceof Doc ? this.layoutDoc.dragFactory : this.layoutDoc); - const referenceLayout = Doc.Layout(referenceDoc); + const refLayout = Doc.Layout(referenceDoc); return <button className="fontIconBox-outerDiv" title={StrCast(this.layoutDoc.title)} ref={this._ref} onContextMenu={this.specificContextMenu} style={{ - background: StrCast(referenceLayout.backgroundColor), + padding: Cast(this.layoutDoc._xPadding, "number", null), + background: StrCast(refLayout._backgroundColor, StrCast(refLayout.backgroundColor)), boxShadow: this.layoutDoc.ischecked ? `4px 4px 12px black` : undefined }}> - <FontAwesomeIcon className="fontIconBox-icon" icon={this.dataDoc.icon as any} color={this._foregroundColor} size="sm" /> + <FontAwesomeIcon className="fontIconBox-icon" icon={this.dataDoc.icon as any} color={StrCast(this.layoutDoc.color, this._foregroundColor)} size="sm" /> {!this.rootDoc.label ? (null) : <div className="fontIconBox-label"> {StrCast(this.rootDoc.label).substring(0, 5)} </div>} </button>; } diff --git a/src/client/views/nodes/ImageBox.scss b/src/client/views/nodes/ImageBox.scss index 15148d01d..c1b95b308 100644 --- a/src/client/views/nodes/ImageBox.scss +++ b/src/client/views/nodes/ImageBox.scss @@ -2,7 +2,7 @@ border-radius: inherit; width: 100%; height: 100%; - position: absolute; + position: relative; transform-origin: top left; .imageBox-fader { diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index c1c6f6baf..d16aa528c 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -120,7 +120,7 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps, ImageD }); const files = await res.json(); const url = Utils.prepend(files[0].path); - // upload to server with known URL + // upload to server with known URL const audioDoc = Docs.Create.AudioDocument(url, { title: "audio test", _width: 200, _height: 32 }); audioDoc.treeViewExpandedView = "layout"; const audioAnnos = Cast(this.dataDoc[this.fieldKey + "-audioAnnotations"], listSpec(Doc)); @@ -174,14 +174,14 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps, ImageD // }), icon: "expand-arrows-alt" // }); - const existingAnalyze = ContextMenu.Instance.findByDescription("Analyzers..."); + const existingAnalyze = ContextMenu.Instance?.findByDescription("Analyzers..."); const modes: ContextMenuProps[] = existingAnalyze && "subitems" in existingAnalyze ? existingAnalyze.subitems : []; modes.push({ description: "Generate Tags", event: this.generateMetadata, icon: "tag" }); modes.push({ description: "Find Faces", event: this.extractFaces, icon: "camera" }); //modes.push({ description: "Recommend", event: this.extractText, icon: "brain" }); - !existingAnalyze && ContextMenu.Instance.addItem({ description: "Analyzers...", subitems: modes, icon: "hand-point-right" }); + !existingAnalyze && ContextMenu.Instance?.addItem({ description: "Analyzers...", subitems: modes, icon: "hand-point-right" }); - ContextMenu.Instance.addItem({ description: "Options...", subitems: funcs, icon: "asterisk" }); + ContextMenu.Instance?.addItem({ description: "Options...", subitems: funcs, icon: "asterisk" }); } } @@ -236,6 +236,7 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps, ImageD if (this._curSuffix === "_m") this._mediumRetryCount++; if (this._curSuffix === "_l") this._largeRetryCount++; } + @action onError = (error: any) => { const timeout = this._curSuffix === "_s" ? this._smallRetryCount : this._curSuffix === "_m" ? this._mediumRetryCount : this._largeRetryCount; if (timeout < 5) { @@ -490,4 +491,4 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps, ImageD </CollectionFreeFormView> </div >); } -}
\ No newline at end of file +} diff --git a/src/client/views/nodes/KeyValueBox.tsx b/src/client/views/nodes/KeyValueBox.tsx index d375466c9..b732f5f83 100644 --- a/src/client/views/nodes/KeyValueBox.tsx +++ b/src/client/views/nodes/KeyValueBox.tsx @@ -169,8 +169,8 @@ export class KeyValueBox extends React.Component<FieldViewProps> { getTemplate = async () => { const parent = Docs.Create.StackingDocument([], { _width: 800, _height: 800, title: "Template" }); - parent.singleColumn = false; - parent.columnWidth = 100; + parent._columnsStack = false; + parent._columnWidth = 100; for (const row of this.rows.filter(row => row.isChecked)) { await this.createTemplateField(parent, row); row.uncheck(); diff --git a/src/client/views/nodes/LinkAnchorBox.scss b/src/client/views/nodes/LinkAnchorBox.scss index 710f2178b..42ef2958e 100644 --- a/src/client/views/nodes/LinkAnchorBox.scss +++ b/src/client/views/nodes/LinkAnchorBox.scss @@ -1,4 +1,5 @@ -.linkAnchorBox-cont, .linkAnchorBox-cont-small { +.linkAnchorBox-cont, +.linkAnchorBox-cont-small { cursor: default; position: absolute; width: 15; @@ -24,6 +25,6 @@ } .linkAnchorBox-cont-small { - width:5px; - height:5px; + width: 5px; + height: 5px; }
\ No newline at end of file diff --git a/src/client/views/nodes/LinkAnchorBox.tsx b/src/client/views/nodes/LinkAnchorBox.tsx index 2bcc6168b..d4ab70200 100644 --- a/src/client/views/nodes/LinkAnchorBox.tsx +++ b/src/client/views/nodes/LinkAnchorBox.tsx @@ -115,8 +115,9 @@ export class LinkAnchorBox extends ViewBoxBaseComponent<FieldViewProps, LinkAnch render() { TraceMobx(); - const x = this.props.PanelWidth() > 1 ? NumCast(this.rootDoc[this.fieldKey + "_x"], 100) : 0; - const y = this.props.PanelWidth() > 1 ? NumCast(this.rootDoc[this.fieldKey + "_y"], 100) : 0; + const small = this.props.PanelWidth() <= 1; // this happens when rendered in a treeView + const x = NumCast(this.rootDoc[this.fieldKey + "_x"], 100); + const y = NumCast(this.rootDoc[this.fieldKey + "_y"], 100); const c = StrCast(this.layoutDoc._backgroundColor, StrCast(this.layoutDoc.backgroundColor, StrCast(this.dataDoc.backgroundColor, "lightBlue"))); // note this is not where the typical lightBlue default color comes from. See Documents.Create.LinkDocument() const anchor = this.fieldKey === "anchor1" ? "anchor2" : "anchor1"; const anchorScale = (x === 0 || x === 100 || y === 0 || y === 100) ? 1 : .25; @@ -131,7 +132,6 @@ export class LinkAnchorBox extends ViewBoxBaseComponent<FieldViewProps, LinkAnch </div>} </div> ); - const small = this.props.PanelWidth() <= 1; return <div className={`linkAnchorBox-cont${small ? "-small" : ""} ${this.rootDoc[Id]}`} onPointerLeave={action(() => LinkDocPreview.LinkInfo = undefined)} onPointerEnter={action(e => LinkDocPreview.LinkInfo = { @@ -143,8 +143,8 @@ export class LinkAnchorBox extends ViewBoxBaseComponent<FieldViewProps, LinkAnch onPointerDown={this.onPointerDown} onClick={this.onClick} title={targetTitle} onContextMenu={this.specificContextMenu} ref={this._ref} style={{ background: c, - left: !small ? `calc(${x}% - 7.5px)` : undefined, - top: !small ? `calc(${y}% - 7.5px)` : undefined, + left: `calc(${x}% - ${small ? 2.5 : 7.5}px)`, + top: `calc(${y}% - ${small ? 2.5 : 7.5}px)`, transform: `scale(${anchorScale / this.props.ContentScaling()})` }} > {!this._editing && !this._forceOpen ? (null) : diff --git a/src/client/views/nodes/LinkCreatedBox.scss b/src/client/views/nodes/LinkCreatedBox.scss new file mode 100644 index 000000000..3cbd38b55 --- /dev/null +++ b/src/client/views/nodes/LinkCreatedBox.scss @@ -0,0 +1,21 @@ +.linkCreatedBox-fade { + border: 1px solid rgb(100, 100, 100); + + + width: auto; + position: absolute; + + height: auto; + z-index: 10000; + border-radius: 13px; + font-size: 13px; + white-space: nowrap; + + color: rgb(100, 100, 100); + background-color: rgba(250, 250, 250, 0.85); + padding-top: 6.5px; + padding-bottom: 6.5px; + font-weight: bold; + padding-left: 9px; + padding-right: 9px; +}
\ No newline at end of file diff --git a/src/client/views/nodes/LinkCreatedBox.tsx b/src/client/views/nodes/LinkCreatedBox.tsx new file mode 100644 index 000000000..d157d3fca --- /dev/null +++ b/src/client/views/nodes/LinkCreatedBox.tsx @@ -0,0 +1,31 @@ +import React = require("react"); +import { observer } from "mobx-react"; +import { documentSchema } from "../../../fields/documentSchemas"; +import { makeInterface } from "../../../fields/Schema"; +import "./LinkCreatedBox.scss"; +import { observable, action } from "mobx"; +import { Fade } from "@material-ui/core"; + + +@observer +export class LinkCreatedBox extends React.Component<{}> { + + @observable public static linkCreated: boolean = false; + @observable public static popupX: number = 600; + @observable public static popupY: number = 250; + + @action + public static changeLinkCreated = () => { + LinkCreatedBox.linkCreated = !LinkCreatedBox.linkCreated; + } + + render() { + return <Fade in={LinkCreatedBox.linkCreated}> + <div className="linkCreatedBox-fade" + style={{ + left: LinkCreatedBox.popupX ? LinkCreatedBox.popupX : 600, + top: LinkCreatedBox.popupY ? LinkCreatedBox.popupY : 250, + }}>Link Created</div> + </Fade>; + } +}
\ No newline at end of file diff --git a/src/client/views/nodes/LinkDocPreview.tsx b/src/client/views/nodes/LinkDocPreview.tsx index 126dc240a..197dc8df4 100644 --- a/src/client/views/nodes/LinkDocPreview.tsx +++ b/src/client/views/nodes/LinkDocPreview.tsx @@ -10,6 +10,11 @@ import { Transform } from "../../util/Transform"; import { ContentFittingDocumentView } from "./ContentFittingDocumentView"; import React = require("react"); import { DocumentView } from './DocumentView'; +import { sortAndDeduplicateDiagnostics } from 'typescript'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { LinkManager } from '../../util/LinkManager'; +import { DocumentLinksButton } from './DocumentLinksButton'; +import { ContextMenu } from '../ContextMenu'; interface Props { linkDoc?: Doc; @@ -24,9 +29,34 @@ export class LinkDocPreview extends React.Component<Props> { @observable public static LinkInfo: Opt<{ linkDoc?: Doc; addDocTab: (document: Doc, where: string) => boolean, linkSrc: Doc; href?: string; Location: number[] }>; @observable _targetDoc: Opt<Doc>; @observable _toolTipText = ""; + _editRef = React.createRef<HTMLDivElement>(); - componentDidUpdate() { this.updatePreview() } - componentDidMount() { this.updatePreview() } + @action + deleteLink = (): void => { + this.props.linkDoc ? LinkManager.Instance.deleteLink(this.props.linkDoc) : null; + //this.props.showLinks(); + LinkDocPreview.LinkInfo = undefined; + DocumentLinksButton.EditLink = undefined; + } + + @action + onContextMenu = (e: React.MouseEvent) => { + DocumentLinksButton.EditLink = undefined; + LinkDocPreview.LinkInfo = undefined; + e.preventDefault(); + ContextMenu.Instance.addItem({ description: "Follow Default Link", event: () => this.followDefault(), icon: "arrow-right" }); + ContextMenu.Instance.displayMenu(e.clientX, e.clientY); + } + + @action.bound + async followDefault() { + DocumentLinksButton.EditLink = undefined; + LinkDocPreview.LinkInfo = undefined; + this._targetDoc ? DocumentManager.Instance.FollowLink(this.props.linkDoc, this._targetDoc, doc => this.props.addDocTab(doc, "onRight"), false) : null; + } + + componentDidUpdate() { this.updatePreview(); } + componentDidMount() { this.updatePreview(); } async updatePreview() { const linkDoc = this.props.linkDoc; const linkSrc = this.props.linkSrc; @@ -56,15 +86,30 @@ export class LinkDocPreview extends React.Component<Props> { this.props.addDocTab(Docs.Create.WebDocument(this.props.href, { title: this.props.href, _width: 200, _height: 400, UseCors: true }), "onRight"); } } - width = () => Math.min(350, NumCast(this._targetDoc?.[WidthSym](), 350)); - height = () => Math.min(350, NumCast(this._targetDoc?.[HeightSym](), 350)); + width = () => Math.min(225, NumCast(this._targetDoc?.[WidthSym](), 225)); + height = () => Math.min(225, NumCast(this._targetDoc?.[HeightSym](), 225)); @computed get targetDocView() { return !this._targetDoc ? - <div style={{ pointerEvents: "all", maxWidth: 350, maxHeight: 250, width: "100%", height: "100%", overflow: "hidden" }}> + <div style={{ + pointerEvents: "all", maxWidth: 225, maxHeight: 225, width: "100%", height: "100%", + overflow: "hidden" + }}> <div style={{ width: "100%", height: "100%", textOverflow: "ellipsis", }} onPointerDown={this.pointerDown}> {this._toolTipText} </div> </div> : + // <div style={{ + // border: "6px solid white", + // }}> + // <div style={{ backgroundColor: "white" }}> {this._targetDoc.title} + // <div className="wrapper" style={{ float: "right" }}> + // <div title="Delete link" className="button" style={{ display: "inline" }} ref={this._editRef} onPointerDown={this.deleteLink}> + // <FontAwesomeIcon className="fa-icon" icon="trash" size="sm" /></div> + // <div title="Follow link" className="button" style={{ display: "inline" }} onClick={this.followDefault} onContextMenu={this.onContextMenu}> + // <FontAwesomeIcon className="fa-icon" icon="arrow-right" size="sm" /> + // </div> + // </div> + // </div> <ContentFittingDocumentView Document={this._targetDoc} LibraryPath={emptyPath} @@ -92,6 +137,7 @@ export class LinkDocPreview extends React.Component<Props> { NativeWidth={returnZero} NativeHeight={returnZero} />; + //</div>; } render() { @@ -99,9 +145,9 @@ export class LinkDocPreview extends React.Component<Props> { style={{ position: "absolute", left: this.props.location[0], top: this.props.location[1], width: this.width(), height: this.height(), - boxShadow: "black 2px 2px 1em" + boxShadow: "black 2px 2px 1em", zIndex: 1000 }}> {this.targetDocView} </div>; } -}
\ No newline at end of file +} diff --git a/src/client/views/nodes/PDFBox.scss b/src/client/views/nodes/PDFBox.scss index 3e09fe519..f2ab37984 100644 --- a/src/client/views/nodes/PDFBox.scss +++ b/src/client/views/nodes/PDFBox.scss @@ -1,28 +1,30 @@ .pdfBox, .pdfBox-interactive { display: inline-block; - position: absolute; + position: relative; height: 100%; width: 100%; overflow: hidden; - cursor:auto; + cursor: auto; transform-origin: top left; z-index: 0; + .pdfBox-ui { position: absolute; - width: 100%; - height: 100%; - z-index: 1; - pointer-events: none; + width: 100%; + height: 100%; + z-index: 1; + pointer-events: none; - .pdfBox-pageNums { + .pdfBox-pageNums { display: flex; flex-direction: row; height: 25px; position: absolute; left: 5px; top: 5px; - .pdfBox-overlayButton-fwd, + + .pdfBox-overlayButton-fwd, .pdfBox-overlayButton-back { background: #121721; height: 25px; @@ -34,29 +36,29 @@ border-radius: 3px; pointer-events: all; } - } - - .pdfBox-overlayButton { - border-bottom-left-radius: 50%; - display: flex; - justify-content: space-evenly; - align-items: center; - height: 20px; - background: none; - padding: 0; - position: absolute; - pointer-events: all; - - .pdfBox-overlayButton-arrow { - width: 0; - height: 0; - border-top: 10px solid transparent; - border-bottom: 10px solid transparent; - border-right: 15px solid #121721; - transition: all 0.5s; - } - - .pdfBox-overlayButton-iconCont { + } + + .pdfBox-overlayButton { + border-bottom-left-radius: 50%; + display: flex; + justify-content: space-evenly; + align-items: center; + height: 20px; + background: none; + padding: 0; + position: absolute; + pointer-events: all; + + .pdfBox-overlayButton-arrow { + width: 0; + height: 0; + border-top: 10px solid transparent; + border-bottom: 10px solid transparent; + border-right: 15px solid #121721; + transition: all 0.5s; + } + + .pdfBox-overlayButton-iconCont { background: #121721; height: 20px; width: 25px; @@ -66,11 +68,11 @@ justify-content: center; border-radius: 3px; pointer-events: all; - } + } } - .pdfBox-nextIcon, - .pdfBox-prevIcon { + .pdfBox-nextIcon, + .pdfBox-prevIcon { background: #121721; height: 20px; width: 25px; @@ -81,96 +83,97 @@ border-radius: 3px; pointer-events: all; padding: 0px; - } - - .pdfBox-overlayButton:hover { - background: none; - } - - - .pdfBox-settingsCont { - position: absolute; - right: 0; - top: 3; - pointer-events: all; - - .pdfBox-settingsButton { - border-bottom-left-radius: 50%; - display: flex; - justify-content: space-evenly; - align-items: center; - height: 20px; - background: none; - padding: 0; - - .pdfBox-settingsButton-arrow { - width: 0; - height: 0; - border-top: 10px solid transparent; - border-bottom: 10px solid transparent; - border-right: 15px solid #121721; - transition: all 0.5s; - } - - .pdfBox-settingsButton-iconCont { - background: #121721; - height: 20px; - width: 25px; - display: flex; - justify-content: center; - align-items: center; - margin-left: -2px; - border-radius: 3px; - } - } - - .pdfBox-settingsButton:hover { - background: none; - } - - .pdfBox-settingsFlyout { - position: absolute; - background: #323232; - box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.25); - right: 20px; - border-radius: 7px; - padding: 20px; - display: flex; - flex-direction: column; - font-size: 14px; - transition: all 0.5s; - - .pdfBox-settingsFlyout-title { - color: white; - } - - .pdfBox-settingsFlyout-kvpInput { - margin-top: 20px; - display: grid; - grid-template-columns: 47.5% 5% 47.5%; - } - } - } - - .pdfBox-overlayCont { - position: absolute; - width: calc(100% - 40px); - height: 20px; - background: #121721; - bottom: 0; - display: flex; - justify-content: center; - align-items: center; - overflow: hidden; - transition: left .5s; - pointer-events: all; - - .pdfBox-searchBar { - width: 70%; - font-size: 14px; - } - } + } + + .pdfBox-overlayButton:hover { + background: none; + } + + + .pdfBox-settingsCont { + position: absolute; + right: 0; + top: 3; + pointer-events: all; + + .pdfBox-settingsButton { + border-bottom-left-radius: 50%; + display: flex; + justify-content: space-evenly; + align-items: center; + height: 20px; + background: none; + padding: 0; + + .pdfBox-settingsButton-arrow { + width: 0; + height: 0; + border-top: 10px solid transparent; + border-bottom: 10px solid transparent; + border-right: 15px solid #121721; + transition: all 0.5s; + } + + .pdfBox-settingsButton-iconCont { + background: #121721; + height: 20px; + width: 25px; + display: flex; + justify-content: center; + align-items: center; + margin-left: -2px; + border-radius: 3px; + } + } + + .pdfBox-settingsButton:hover { + background: none; + } + + .pdfBox-settingsFlyout { + position: absolute; + background: #323232; + box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.25); + right: 20px; + border-radius: 7px; + padding: 20px; + display: flex; + flex-direction: column; + font-size: 14px; + transition: all 0.5s; + + .pdfBox-settingsFlyout-title { + color: white; + } + + .pdfBox-settingsFlyout-kvpInput { + margin-top: 20px; + display: grid; + grid-template-columns: 47.5% 5% 47.5%; + } + } + } + + .pdfBox-overlayCont { + position: absolute; + width: calc(100% - 40px); + height: 20px; + background: #121721; + bottom: 0; + display: flex; + justify-content: center; + align-items: center; + overflow: hidden; + transition: left .5s; + pointer-events: all; + + .pdfBox-searchBar { + width: 70%; + font-size: 14px; + } + } } + .pdfBox-title-outer { width: 150%; height: 100%; @@ -179,9 +182,9 @@ z-index: 0; background: lightslategray; transform-origin: top left; - + .pdfBox-title { - color:lightgray; + color: lightgray; margin-top: auto; margin-bottom: auto; transform-origin: 42% 15%; @@ -199,7 +202,7 @@ } .pdfBox { - .pdfViewer-text { + .pdfViewerDash-text { .textLayer { span { user-select: none; @@ -210,11 +213,83 @@ .pdfBox-interactive { pointer-events: all; - .pdfViewer-text { + .pdfViewerDash-text { .textLayer { span { user-select: text; } } } -}
\ No newline at end of file +} + +// CSS adjusted for mobile devices +@media only screen and (max-device-width: 480px) { + + .pdfBox .pdfBox-ui .pdfBox-settingsCont .pdfBox-settingsButton, + .pdfBox-interactive .pdfBox-ui .pdfBox-settingsCont .pdfBox-settingsButton { + height: 60px; + + .pdfBox-settingsButton-iconCont { + height: 60px; + width: 75px; + font-size: 30px; + } + + .pdfBox-settingsButton-arrow { + height: 60; + border-top: 30px solid transparent; + border-bottom: 30px solid transparent; + border-right: 30px solid #121721; + } + } + + + + .pdfBox .pdfBox-ui .pdfBox-settingsCont .pdfBox-settingsFlyout, + .pdfBox-interactive .pdfBox-ui .pdfBox-settingsCont .pdfBox-settingsFlyout { + font-size: 30px; + } + + + + .pdfBox .pdfBox-ui .pdfBox-overlayCont, + .pdfBox-interactive .pdfBox-ui .pdfBox-overlayCont { + height: 60px; + + .pdfBox-searchBar { + font-size: 40px; + } + } + + .pdfBox .pdfBox-ui .pdfBox-overlayButton, + .pdfBox-interactive .pdfBox-ui .pdfBox-overlayButton { + height: 60px; + + .pdfBox-overlayButton-iconCont { + height: 60px; + width: 75px; + font-size: 30; + } + + .pdfBox-overlayButton-arrow { + border-top: 30px solid transparent; + border-bottom: 30px solid transparent; + border-right: 30px solid #121721; + } + } + + button.pdfBox-search { + font-size: 30px; + width: 50px; + height: 50px; + } + + .pdfBox .pdfBox-ui .pdfBox-nextIcon, + .pdfBox .pdfBox-ui .pdfBox-prevIcon, + .pdfBox-interactive .pdfBox-ui .pdfBox-nextIcon, + .pdfBox-interactive .pdfBox-ui .pdfBox-prevIcon { + height: 50px; + width: 50px; + font-size: 30px; + } +} diff --git a/src/client/views/nodes/PDFBox.tsx b/src/client/views/nodes/PDFBox.tsx index 6b1c9fcde..1c5825a8f 100644 --- a/src/client/views/nodes/PDFBox.tsx +++ b/src/client/views/nodes/PDFBox.tsx @@ -55,25 +55,28 @@ export class PDFBox extends ViewBoxAnnotatableComponent<FieldViewProps, PdfDocum const backup = "oldPath"; const { Document } = this.props; - const { url: { href } } = Cast(this.dataDoc[this.props.fieldKey], PdfField)!; - const pathCorrectionTest = /upload\_[a-z0-9]{32}.(.*)/g; - const matches = pathCorrectionTest.exec(href); - console.log("\nHere's the { url } being fed into the outer regex:"); - console.log(href); - console.log("And here's the 'properPath' build from the captured filename:\n"); - if (matches !== null && href.startsWith(window.location.origin)) { - const properPath = Utils.prepend(`/files/pdfs/${matches[0]}`); - console.log(properPath); - if (!properPath.includes(href)) { - console.log(`The two (url and proper path) were not equal`); - const proto = Doc.GetProto(Document); - proto[this.props.fieldKey] = new PdfField(properPath); - proto[backup] = href; + const pdf = Cast(this.dataDoc[this.props.fieldKey], PdfField); + const href = pdf?.url?.href; + if (href) { + const pathCorrectionTest = /upload\_[a-z0-9]{32}.(.*)/g; + const matches = pathCorrectionTest.exec(href); + console.log("\nHere's the { url } being fed into the outer regex:"); + console.log(href); + console.log("And here's the 'properPath' build from the captured filename:\n"); + if (matches !== null && href.startsWith(window.location.origin)) { + const properPath = Utils.prepend(`/files/pdfs/${matches[0]}`); + console.log(properPath); + if (!properPath.includes(href)) { + console.log(`The two (url and proper path) were not equal`); + const proto = Doc.GetProto(Document); + proto[this.props.fieldKey] = new PdfField(properPath); + proto[backup] = href; + } else { + console.log(`The two (url and proper path) were equal`); + } } else { - console.log(`The two (url and proper path) were equal`); + console.log("Outer matches was null!"); } - } else { - console.log("Outer matches was null!"); } } @@ -154,7 +157,7 @@ export class PDFBox extends ViewBoxAnnotatableComponent<FieldViewProps, PdfDocum <div className="pdfBox-overlayCont" key="cont" onPointerDown={(e) => e.stopPropagation()} style={{ left: `${this._searching ? 0 : 100}%` }}> <button className="pdfBox-overlayButton" title={searchTitle} /> <input className="pdfBox-searchBar" placeholder="Search" ref={this._searchRef} onChange={this.searchStringChanged} onKeyDown={e => e.keyCode === KeyCodes.ENTER && this.search(this._searchString, !e.shiftKey)} /> - <button title="Search" onClick={e => this.search(this._searchString, !e.shiftKey)}> + <button className="pdfBox-search" title="Search" onClick={e => this.search(this._searchString, !e.shiftKey)}> <FontAwesomeIcon icon="search" size="sm" color="white" /></button> <button className="pdfBox-prevIcon " title="Previous Annotation" onClick={this.prevAnnotation} > <FontAwesomeIcon style={{ color: "white" }} icon={"arrow-up"} size="lg" /> @@ -186,7 +189,7 @@ export class PDFBox extends ViewBoxAnnotatableComponent<FieldViewProps, PdfDocum <FontAwesomeIcon style={{ color: "white" }} icon="cog" size="lg" /> </div> </button> - <div className="pdfBox-settingsFlyout" style={{ right: `${this._flyout ? 20 : -600}px` }} > + <div className="pdfBox-settingsFlyout" style={{ right: `${this._flyout ? 20 : -1000}px` }} > <div className="pdfBox-settingsFlyout-title"> Annotation View Settings </div> @@ -226,7 +229,8 @@ export class PDFBox extends ViewBoxAnnotatableComponent<FieldViewProps, PdfDocum const classname = "pdfBox" + (this.active() ? "-interactive" : ""); return <div className={classname} style={{ width: !this.props.Document._fitWidth ? this.Document._nativeWidth || 0 : `${100 / this.contentScaling}%`, - height: !this.props.Document._fitWidth ? this.Document._nativeHeight || 0 : `${100 / this.contentScaling}%`, + //height adjusted for mobile (window.screen.width > 600) + height: !this.props.Document._fitWidth && (window.screen.width > 600) ? this.Document._nativeHeight || 0 : `${100 / this.contentScaling}%`, transform: `scale(${this.contentScaling})` }} > <div className="pdfBox-title-outer"> @@ -238,7 +242,7 @@ export class PDFBox extends ViewBoxAnnotatableComponent<FieldViewProps, PdfDocum isChildActive = (outsideReaction?: boolean) => this._isChildActive; @computed get renderPdfView() { const pdfUrl = Cast(this.dataDoc[this.props.fieldKey], PdfField); - return <div className={"pdfBox"} onContextMenu={this.specificContextMenu} style={{ height: this.props.Document._scrollTop && !this.Document._fitWidth ? NumCast(this.Document._height) * this.props.PanelWidth() / NumCast(this.Document._width) : undefined }}> + return <div className={"pdfBox"} onContextMenu={this.specificContextMenu} style={{ height: this.props.Document._scrollTop && !this.Document._fitWidth && (window.screen.width > 600) ? NumCast(this.Document._height) * this.props.PanelWidth() / NumCast(this.Document._width) : undefined }}> <PDFViewer {...this.props} pdf={this._pdf!} url={pdfUrl!.url.pathname} active={this.props.active} loaded={this.loaded} setPdfViewer={this.setPdfViewer} ContainingCollectionView={this.props.ContainingCollectionView} renderDepth={this.props.renderDepth} PanelHeight={this.props.PanelHeight} PanelWidth={this.props.PanelWidth} diff --git a/src/client/views/nodes/PresBox.scss b/src/client/views/nodes/PresBox.scss index d48000e16..9f6af1bde 100644 --- a/src/client/views/nodes/PresBox.scss +++ b/src/client/views/nodes/PresBox.scss @@ -16,6 +16,7 @@ height: calc(100% - 25px); width: 100%; } + .presBox-buttons { width: 100%; background: gray; @@ -24,6 +25,7 @@ display: grid; grid-column-end: 4; grid-column-start: 1; + .presBox-viewPicker { height: 25; position: relative; @@ -31,10 +33,12 @@ grid-column: 1/2; min-width: 15px; } + select { background: #323232; color: white; } + .presBox-button { margin-right: 2.5%; margin-left: 2.5%; @@ -44,10 +48,12 @@ align-items: center; background: #323232; color: white; + svg { margin: auto; } } + .collectionViewBaseChrome-viewPicker { min-width: 50; width: 5%; @@ -56,17 +62,68 @@ display: inline-block; } } - .presBox-backward, .presBox-forward { + + .presBox-backward, + .presBox-forward { width: 25px; border-radius: 5px; - top:50%; + top: 50%; position: absolute; display: inline-block; } + .presBox-backward { - left:5; + left: 5; } + .presBox-forward { - right:5; + right: 5; + } +} + +// CSS adjusted for mobile devices +@media only screen and (max-device-width: 480px) { + .presBox-cont .presBox-buttons { + position: absolute; + top: 70%; + left: 50%; + transform: translate(-50%, 0); + width: max-content; + height: 15%; + z-index: 2; + align-items: center; + background: rgba(0, 0, 0, 0); + display: inline-flex; + + .presBox-button { + margin-top: 5%; + height: 250; + width: 300; + font-size: 100; + display: flex; + align-items: center; + background: #323232; + color: white; + } + + .presBox-viewPicker { + top: -70; + left: 2.5%; + height: 50; + width: 95%; + font-size: 30px; + position: absolute; + min-width: 50px; + } + } + + .presBox-cont .presBox-listCont { + top: 50; + height: calc(100% - 80px); + } + + .input, + .select { + font-size: 100%; } }
\ No newline at end of file diff --git a/src/client/views/nodes/PresBox.tsx b/src/client/views/nodes/PresBox.tsx index dbc879920..8818d375e 100644 --- a/src/client/views/nodes/PresBox.tsx +++ b/src/client/views/nodes/PresBox.tsx @@ -62,8 +62,8 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps, PresBoxSchema> const lastFrame = Cast(presTargetDoc.lastFrame, "number", null); const curFrame = NumCast(presTargetDoc.currentFrame); if (lastFrame !== undefined && curFrame < lastFrame) { - presTargetDoc.transition = "all 1s"; - setTimeout(() => presTargetDoc.transition = undefined, 1010); + presTargetDoc._viewTransition = "all 1s"; + setTimeout(() => presTargetDoc._viewTransition = undefined, 1010); presTargetDoc.currentFrame = curFrame + 1; } else if (this.childDocs[this.itemIndex + 1] !== undefined) { diff --git a/src/client/views/nodes/RadialMenu.tsx b/src/client/views/nodes/RadialMenu.tsx index ddfdb67b4..a3ac09a11 100644 --- a/src/client/views/nodes/RadialMenu.tsx +++ b/src/client/views/nodes/RadialMenu.tsx @@ -1,7 +1,6 @@ import React = require("react"); import { action, computed, IReactionDisposer, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; -import MobileInterface from "../../../mobile/MobileInterface"; import "./RadialMenu.scss"; import { RadialMenuItem, RadialMenuProps } from "./RadialMenuItem"; @@ -26,7 +25,6 @@ export class RadialMenu extends React.Component { catchTouch = (te: React.TouchEvent) => { - console.log("caught"); te.stopPropagation(); te.preventDefault(); } @@ -38,7 +36,6 @@ export class RadialMenu extends React.Component { this._mouseY = e.clientY; this.used = false; document.addEventListener("pointermove", this.onPointerMove); - } @observable @@ -176,7 +173,6 @@ export class RadialMenu extends React.Component { @action openMenu = (x: number, y: number) => { - this._pageX = x; this._pageY = y; this._shouldDisplay; @@ -216,7 +212,7 @@ export class RadialMenu extends React.Component { render() { - if (!this._display || MobileInterface.Instance) { + if (!this._display) { return null; } const style = this._yRelativeToTop ? { left: this._pageX - 130, top: this._pageY - 130 } : diff --git a/src/client/views/nodes/VideoBox.tsx b/src/client/views/nodes/VideoBox.tsx index 71556bfd3..a5c6c4a48 100644 --- a/src/client/views/nodes/VideoBox.tsx +++ b/src/client/views/nodes/VideoBox.tsx @@ -19,6 +19,7 @@ import { FieldView, FieldViewProps } from './FieldView'; import "./VideoBox.scss"; import { documentSchema } from "../../../fields/documentSchemas"; import { Networking } from "../../Network"; +import { SnappingManager } from "../../util/SnappingManager"; const path = require('path'); export const timeSchema = createSchema({ @@ -58,21 +59,21 @@ export class VideoBox extends ViewBoxAnnotatableComponent<FieldViewProps, VideoD @action public Play = (update: boolean = true) => { this._playing = true; - update && this.player && this.player.play(); - update && this._youtubePlayer && this._youtubePlayer.playVideo(); + update && this.player?.play(); + update && this._youtubePlayer?.playVideo(); this._youtubePlayer && !this._playTimer && (this._playTimer = setInterval(this.updateTimecode, 5)); this.updateTimecode(); } @action public Seek(time: number) { - this._youtubePlayer && this._youtubePlayer.seekTo(Math.round(time), true); + this._youtubePlayer?.seekTo(Math.round(time), true); this.player && (this.player.currentTime = time); } @action public Pause = (update: boolean = true) => { this._playing = false; - update && this.player && this.player.pause(); - update && this._youtubePlayer && this._youtubePlayer.pauseVideo && this._youtubePlayer.pauseVideo(); + update && this.player?.pause(); + update && this._youtubePlayer?.pauseVideo(); this._youtubePlayer && this._playTimer && clearInterval(this._playTimer); this._playTimer = undefined; this.updateTimecode(); @@ -261,21 +262,20 @@ export class VideoBox extends ViewBoxAnnotatableComponent<FieldViewProps, VideoD const onYoutubePlayerStateChange = (event: any) => runInAction(() => { if (started && event.data === YT.PlayerState.PLAYING) { started = false; - this._youtubePlayer && this._youtubePlayer.unMute(); - this.Pause(); + this._youtubePlayer?.unMute(); + //this.Pause(); return; } if (event.data === YT.PlayerState.PLAYING && !this._playing) this.Play(false); if (event.data === YT.PlayerState.PAUSED && this._playing) this.Pause(false); }); const onYoutubePlayerReady = (event: any) => { - this._reactionDisposer && this._reactionDisposer(); - this._youtubeReactionDisposer && this._youtubeReactionDisposer(); + this._reactionDisposer?.(); + this._youtubeReactionDisposer?.(); this._reactionDisposer = reaction(() => this.layoutDoc.currentTimecode, () => !this._playing && this.Seek((this.layoutDoc.currentTimecode || 0))); - this._youtubeReactionDisposer = reaction(() => [this.props.isSelected(), DocumentDecorations.Instance.Interacting, Doc.GetSelectedTool()], () => { - const interactive = Doc.GetSelectedTool() === InkTool.None && this.props.isSelected(true) && !DocumentDecorations.Instance.Interacting; - iframe.style.pointerEvents = interactive ? "all" : "none"; - }, { fireImmediately: true }); + this._youtubeReactionDisposer = reaction( + () => Doc.GetSelectedTool() === InkTool.None && this.props.isSelected(true) && !SnappingManager.GetIsDragging() && !DocumentDecorations.Instance.Interacting, + (interactive) => iframe.style.pointerEvents = interactive ? "all" : "none", { fireImmediately: true }); }; this._youtubePlayer = new YT.Player(`${this.youtubeVideoId + this._youtubeIframeId}-player`, { events: { @@ -346,7 +346,7 @@ export class VideoBox extends ViewBoxAnnotatableComponent<FieldViewProps, VideoD const start = untracked(() => Math.round((this.layoutDoc.currentTimecode || 0))); return <iframe key={this._youtubeIframeId} id={`${this.youtubeVideoId + this._youtubeIframeId}-player`} onLoad={this.youtubeIframeLoaded} className={`${style}`} width={(this.layoutDoc._nativeWidth || 640)} height={(this.layoutDoc._nativeHeight || 390)} - src={`https://www.youtube.com/embed/${this.youtubeVideoId}?enablejsapi=1&rel=0&showinfo=1&autoplay=1&mute=1&start=${start}&modestbranding=1&controls=${VideoBox._showControls ? 1 : 0}`} />; + src={`https://www.youtube.com/embed/${this.youtubeVideoId}?enablejsapi=1&rel=0&showinfo=1&autoplay=0&mute=1&start=${start}&modestbranding=1&controls=${VideoBox._showControls ? 1 : 0}`} />; } @action.bound diff --git a/src/client/views/nodes/formattedText/DashFieldView.tsx b/src/client/views/nodes/formattedText/DashFieldView.tsx index 8c16f4a1a..8718bf329 100644 --- a/src/client/views/nodes/formattedText/DashFieldView.tsx +++ b/src/client/views/nodes/formattedText/DashFieldView.tsx @@ -184,9 +184,9 @@ export class DashFieldViewInternal extends React.Component<IDashFieldViewInterna if (container) { const alias = Doc.MakeAlias(container.props.Document); alias.viewType = CollectionViewType.Time; - let list = Cast(alias.schemaColumns, listSpec(SchemaHeaderField)); + let list = Cast(alias._columnHeaders, listSpec(SchemaHeaderField)); if (!list) { - alias.schemaColumns = list = new List<SchemaHeaderField>(); + alias._columnHeaders = list = new List<SchemaHeaderField>(); } list.map(c => c.heading).indexOf(this._fieldKey) === -1 && list.push(new SchemaHeaderField(this._fieldKey, "#f1efeb")); list.map(c => c.heading).indexOf("text") === -1 && list.push(new SchemaHeaderField("text", "#f1efeb")); diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.scss b/src/client/views/nodes/formattedText/FormattedTextBox.scss index 20e13a599..afdd8fea2 100644 --- a/src/client/views/nodes/formattedText/FormattedTextBox.scss +++ b/src/client/views/nodes/formattedText/FormattedTextBox.scss @@ -37,6 +37,7 @@ position: absolute; } } + .formattedTextBox-outer { position: relative; overflow: auto; @@ -72,7 +73,7 @@ .collectionfreeformview-container { position: relative; } - + >.formattedTextBox-sidebar-handle { right: unset; left: -5; @@ -95,7 +96,7 @@ .formattedTextBox-inner-rounded, .formattedTextBox-inner-rounded-selected, .formattedTextBox-inner, .formattedTextBox-inner-selected { height: 100%; - white-space: pre-wrap; + white-space: pre-wrap; .ProseMirror:hover { background: rgba(200,200,200,0.8); } @@ -262,19 +263,19 @@ footnote::after { border:unset; padding:0px; } - + .prosemirror-links a { float: left; color: white; text-decoration: none; border-radius: 3px; } - + .prosemirror-links a:hover { background-color: #eee; color: black; } - + .prosemirror-anchor:hover .prosemirror-links { display: grid; } @@ -302,40 +303,39 @@ footnote::after { font-family: inherit; } ol { - margin-left: 1em; font-family: inherit; } - .bullet { p {display: inline; font-family: inherit} margin-left: 0; } - .bullet1 { p {display: inline; font-family: inherit} } - .bullet2,.bullet3,.bullet4,.bullet5,.bullet6 { p {display: inline; font-family: inherit} font-size: smaller; } - - .decimal1-ol { counter-reset: deci1; p {display: inline; font-family: inherit} margin-left: 0; } - .decimal2-ol { counter-reset: deci2; p {display: inline; font-family: inherit} font-size: smaller; padding-left: 1em;} - .decimal3-ol { counter-reset: deci3; p {display: inline; font-family: inherit} font-size: smaller; padding-left: 2em;} - .decimal4-ol { counter-reset: deci4; p {display: inline; font-family: inherit} font-size: smaller; padding-left: 3em;} - .decimal5-ol { counter-reset: deci5; p {display: inline; font-family: inherit} font-size: smaller; } - .decimal6-ol { counter-reset: deci6; p {display: inline; font-family: inherit} font-size: smaller; } - .decimal7-ol { counter-reset: deci7; p {display: inline; font-family: inherit} font-size: smaller; } - - .multi1-ol { counter-reset: multi1; p {display: inline; font-family: inherit} margin-left: 0; padding-left: 1.2em } - .multi2-ol { counter-reset: multi2; p {display: inline; font-family: inherit} font-size: smaller; padding-left: 1.4em;} - .multi3-ol { counter-reset: multi3; p {display: inline; font-family: inherit} font-size: smaller; padding-left: 2em;} - .multi4-ol { counter-reset: multi4; p {display: inline; font-family: inherit} font-size: smaller; padding-left: 3.4em;} - - .bullet:before, .bullet1:before, .bullet2:before, .bullet3:before, .bullet4:before, .bullet5:before { transition: 0.5s; display: inline-block; margin-left: -1em; width: 1em; content:" " } - - .decimal1:before { transition: 0.5s;counter-increment: deci1; display: inline-block; margin-left: -1em; width: 1em; content: counter(deci1) ". "; } - .decimal2:before { transition: 0.5s;counter-increment: deci2; display: inline-block; margin-left: -2.1em; width: 2.1em; content: counter(deci1) "."counter(deci2) ". "; } - .decimal3:before { transition: 0.5s;counter-increment: deci3; display: inline-block; margin-left: -2.85em;width: 2.85em; content: counter(deci1) "."counter(deci2) "."counter(deci3) ". "; } - .decimal4:before { transition: 0.5s;counter-increment: deci4; display: inline-block; margin-left: -3.85em;width: 3.85em; content: counter(deci1) "."counter(deci2) "."counter(deci3) "."counter(deci4) ". "; } - .decimal5:before { transition: 0.5s;counter-increment: deci5; display: inline-block; margin-left: -2em; width: 5em; content: counter(deci1) "."counter(deci2) "."counter(deci3) "."counter(deci4) "."counter(deci5) ". "; } - .decimal6:before { transition: 0.5s;counter-increment: deci6; display: inline-block; margin-left: -2em; width: 6em; content: counter(deci1) "."counter(deci2) "."counter(deci3) "."counter(deci4) "."counter(deci5) "."counter(deci6) ". "; } - .decimal7:before { transition: 0.5s;counter-increment: deci7; display: inline-block; margin-left: -2em; width: 7em; content: counter(deci1) "."counter(deci2) "."counter(deci3) "."counter(deci4) "."counter(deci5) "."counter(deci6) "."counter(deci7) ". "; } - - .multi1:before { transition: 0.5s;counter-increment: multi1; display: inline-block; margin-left: -1em; width: 1.2em; content: counter(multi1, upper-alpha) ". "; } - .multi2:before { transition: 0.5s;counter-increment: multi2; display: inline-block; margin-left: -2em; width: 2em; content: counter(multi1, upper-alpha) "."counter(multi2, decimal) ". "; } - .multi3:before { transition: 0.5s;counter-increment: multi3; display: inline-block; margin-left: -2.85em; width:2.85em; content: counter(multi1, upper-alpha) "."counter(multi2, decimal) "."counter(multi3, lower-alpha) ". "; } - .multi4:before { transition: 0.5s;counter-increment: multi4; display: inline-block; margin-left: -4.2em; width: 4.2em; content: counter(multi1, upper-alpha) "."counter(multi2, decimal) "."counter(multi3, lower-alpha) "."counter(multi4, lower-roman) ". "; } + .bullet { p { font-family: inherit} margin-left: 0; } + .bullet1 { p { font-family: inherit} } + .bullet2,.bullet3,.bullet4,.bullet5,.bullet6 { p { font-family: inherit} font-size: smaller; } + + .decimal1-ol { counter-reset: deci1; p {display: inline-block; font-family: inherit} margin-left: 0; } + .decimal2-ol { counter-reset: deci2; p {display: inline-block; font-family: inherit} font-size: smaller; padding-left: 2.1em;} + .decimal3-ol { counter-reset: deci3; p {display: inline-block; font-family: inherit} font-size: smaller; padding-left: 2.85em;} + .decimal4-ol { counter-reset: deci4; p {display: inline-block; font-family: inherit} font-size: smaller; padding-left: 3.85em;} + .decimal5-ol { counter-reset: deci5; p {display: inline-block; font-family: inherit} font-size: smaller; } + .decimal6-ol { counter-reset: deci6; p {display: inline-block; font-family: inherit} font-size: smaller; } + .decimal7-ol { counter-reset: deci7; p {display: inline-block; font-family: inherit} font-size: smaller; } + + .multi1-ol { counter-reset: multi1; p {display: inline-block; font-family: inherit} margin-left: 0; padding-left: 1.2em } + .multi2-ol { counter-reset: multi2; p {display: inline-block; font-family: inherit} font-size: smaller; padding-left: 2em;} + .multi3-ol { counter-reset: multi3; p {display: inline-block; font-family: inherit} font-size: smaller; padding-left: 2.85em;} + .multi4-ol { counter-reset: multi4; p {display: inline-block; font-family: inherit} font-size: smaller; padding-left: 3.85em;} + + //.bullet:before, .bullet1:before, .bullet2:before, .bullet3:before, .bullet4:before, .bullet5:before { transition: 0.5s; display: inline-block; vertical-align: top; margin-left: -1em; width: 1em; content:" " } + + .decimal1:before { transition: 0.5s;counter-increment: deci1; display: inline-block; vertical-align: top; margin-left: -1em; width: 1em; content: counter(deci1) ". "; } + .decimal2:before { transition: 0.5s;counter-increment: deci2; display: inline-block; vertical-align: top; margin-left: -2.1em; width: 2.1em; content: counter(deci1) "."counter(deci2) ". "; } + .decimal3:before { transition: 0.5s;counter-increment: deci3; display: inline-block; vertical-align: top; margin-left: -2.85em;width: 2.85em; content: counter(deci1) "."counter(deci2) "."counter(deci3) ". "; } + .decimal4:before { transition: 0.5s;counter-increment: deci4; display: inline-block; vertical-align: top; margin-left: -3.85em;width: 3.85em; content: counter(deci1) "."counter(deci2) "."counter(deci3) "."counter(deci4) ". "; } + .decimal5:before { transition: 0.5s;counter-increment: deci5; display: inline-block; vertical-align: top; margin-left: -2em; width: 5em; content: counter(deci1) "."counter(deci2) "."counter(deci3) "."counter(deci4) "."counter(deci5) ". "; } + .decimal6:before { transition: 0.5s;counter-increment: deci6; display: inline-block; vertical-align: top; margin-left: -2em; width: 6em; content: counter(deci1) "."counter(deci2) "."counter(deci3) "."counter(deci4) "."counter(deci5) "."counter(deci6) ". "; } + .decimal7:before { transition: 0.5s;counter-increment: deci7; display: inline-block; vertical-align: top; margin-left: -2em; width: 7em; content: counter(deci1) "."counter(deci2) "."counter(deci3) "."counter(deci4) "."counter(deci5) "."counter(deci6) "."counter(deci7) ". "; } + + .multi1:before { transition: 0.5s;counter-increment: multi1; display: inline-block; vertical-align: top; margin-left: -1.3em; width: 1.2em; content: counter(multi1, upper-alpha) ". "; } + .multi2:before { transition: 0.5s;counter-increment: multi2; display: inline-block; vertical-align: top; margin-left: -2em; width: 2em; content: counter(multi1, upper-alpha) "."counter(multi2, decimal) ". "; } + .multi3:before { transition: 0.5s;counter-increment: multi3; display: inline-block; vertical-align: top; margin-left: -2.85em; width:2.85em; content: counter(multi1, upper-alpha) "."counter(multi2, decimal) "."counter(multi3, lower-alpha) ". "; } + .multi4:before { transition: 0.5s;counter-increment: multi4; display: inline-block; vertical-align: top; margin-left: -4.2em; width: 4.2em; content: counter(multi1, upper-alpha) "."counter(multi2, decimal) "."counter(multi3, lower-alpha) "."counter(multi4, lower-roman) ". "; } } .formattedTextBox-inner-rounded-selected, @@ -346,4 +346,284 @@ footnote::after { .ProseMirror:hover { background: unset; } -}
\ No newline at end of file +} + +@media only screen and (max-width: 1000px) { + @import "../../globalCssVariables"; + + .ProseMirror { + width: 100%; + height: 100%; + min-height: 100%; + } + + .ProseMirror:focus { + outline: none !important; + } + + .formattedTextBox-cont { + touch-action: none; + cursor: text; + background: inherit; + padding: 0; + border-width: 0px; + border-radius: inherit; + border-color: $intermediate-color; + box-sizing: border-box; + background-color: inherit; + border-style: solid; + overflow-y: auto; + overflow-x: hidden; + color: initial; + max-height: 100%; + display: flex; + flex-direction: row; + transition: opacity 1s; + + .formattedTextBox-dictation { + height: 12px; + width: 10px; + top: 0px; + left: 0px; + position: absolute; + } + } + + .formattedTextBox-outer { + position: relative; + overflow: auto; + display: inline-block; + width: 100%; + height: 100%; + } + + .formattedTextBox-sidebar-handle { + position: absolute; + top: calc(50% - 17.5px); + width: 10px; + height: 35px; + background: lightgray; + border-radius: 20px; + cursor:grabbing; + } + + .formattedTextBox-cont>.formattedTextBox-sidebar-handle { + right: 0; + left: unset; + } + + .formattedTextBox-sidebar, + .formattedTextBox-sidebar-inking { + border-left: dashed 1px black; + height: 100%; + display: inline-block; + position: absolute; + right: 0; + + .collectionfreeformview-container { + position: relative; + } + + >.formattedTextBox-sidebar-handle { + right: unset; + left: -5; + } + } + + .formattedTextBox-sidebar-inking { + pointer-events: all; + } + + .formattedTextBox-inner-rounded { + height: 70%; + width: 85%; + position: absolute; + overflow: auto; + top: 15%; + left: 10%; + } + + .formattedTextBox-inner-rounded, + .formattedTextBox-inner { + height: 100%; + white-space: pre-wrap; + hr { + display: block; + unicode-bidi: isolate; + margin-block-start: 0.5em; + margin-block-end: 0.5em; + margin-inline-start: auto; + margin-inline-end: auto; + overflow: hidden; + border-style: inset; + border-width: 1px; + } + } + + // .menuicon { + // display: inline-block; + // border-right: 1px solid rgba(0, 0, 0, 0.2); + // color: #888; + // line-height: 1; + // padding: 0 7px; + // margin: 1px; + // cursor: pointer; + // text-align: center; + // min-width: 1.4em; + // } + + .strong, + .heading { + font-weight: bold; + } + + .em { + font-style: italic; + } + + .userMarkOpen { + background: rgba(255, 255, 0, 0.267); + display: inline; + } + + .userMark { + background: rgba(255, 255, 0, 0.267); + font-size: 2px; + display: inline-grid; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + width: 10px; + min-height: 10px; + text-align: center; + align-content: center; + } + + footnote { + display: inline-block; + position: relative; + cursor: pointer; + + div { + padding: 0 !important; + } + } + + footnote::after { + content: counter(prosemirror-footnote); + vertical-align: super; + font-size: 75%; + counter-increment: prosemirror-footnote; + } + + .ProseMirror { + counter-reset: prosemirror-footnote; + } + + .footnote-tooltip { + cursor: auto; + font-size: 75%; + position: absolute; + left: -30px; + top: calc(100% + 10px); + background: silver; + padding: 3px; + border-radius: 2px; + max-width: 100px; + min-width: 50px; + width: max-content; + } + + .prosemirror-attribution { + font-size: 8px; + } + + .footnote-tooltip::before { + border: 5px solid silver; + border-top-width: 0px; + border-left-color: transparent; + border-right-color: transparent; + position: absolute; + top: -5px; + left: 27px; + content: " "; + height: 0; + width: 0; + } + + + .formattedTextBox-inlineComment { + position: relative; + width: 40px; + height: 20px; + &::before { + content: "→"; + } + &:hover { + background: orange; + } + } + + .formattedTextBox-summarizer { + opacity: 0.5; + position: relative; + width: 40px; + height: 20px; + &::after { + content: "←"; + } + } + + .formattedTextBox-summarizer-collapsed { + opacity: 0.5; + position: relative; + width: 40px; + height: 20px; + &::after { + content: "..."; + } + } + + .ProseMirror { + touch-action: none; + span { + font-family: inherit; + } + + ol, ul { + counter-reset: deci1 0 multi1 0; + padding-left: 1em; + font-family: inherit; + } + ol { + margin-left: 1em; + font-family: inherit; + } + + .decimal1-ol { counter-reset: deci1; p {display: inline; font-family: inherit} margin-left: 0; } + .decimal2-ol { counter-reset: deci2; p {display: inline; font-family: inherit} font-size: smaller; padding-left: 1em;} + .decimal3-ol { counter-reset: deci3; p {display: inline; font-family: inherit} font-size: smaller; padding-left: 2em;} + .decimal4-ol { counter-reset: deci4; p {display: inline; font-family: inherit} font-size: smaller; padding-left: 3em;} + .decimal5-ol { counter-reset: deci5; p {display: inline; font-family: inherit} font-size: smaller; } + .decimal6-ol { counter-reset: deci6; p {display: inline; font-family: inherit} font-size: smaller; } + .decimal7-ol { counter-reset: deci7; p {display: inline; font-family: inherit} font-size: smaller; } + + .multi1-ol { counter-reset: multi1; p {display: inline; font-family: inherit} margin-left: 0; padding-left: 1.2em } + .multi2-ol { counter-reset: multi2; p {display: inline; font-family: inherit} font-size: smaller; padding-left: 1.4em;} + .multi3-ol { counter-reset: multi3; p {display: inline; font-family: inherit} font-size: smaller; padding-left: 2em;} + .multi4-ol { counter-reset: multi4; p {display: inline; font-family: inherit} font-size: smaller; padding-left: 3.4em;} + + .decimal1:before { transition: 0.5s;counter-increment: deci1; display: inline-block; margin-left: -1em; width: 1em; content: counter(deci1) ". "; } + .decimal2:before { transition: 0.5s;counter-increment: deci2; display: inline-block; margin-left: -2.1em; width: 2.1em; content: counter(deci1) "."counter(deci2) ". "; } + .decimal3:before { transition: 0.5s;counter-increment: deci3; display: inline-block; margin-left: -2.85em;width: 2.85em; content: counter(deci1) "."counter(deci2) "."counter(deci3) ". "; } + .decimal4:before { transition: 0.5s;counter-increment: deci4; display: inline-block; margin-left: -3.85em;width: 3.85em; content: counter(deci1) "."counter(deci2) "."counter(deci3) "."counter(deci4) ". "; } + .decimal5:before { transition: 0.5s;counter-increment: deci5; display: inline-block; margin-left: -2em; width: 5em; content: counter(deci1) "."counter(deci2) "."counter(deci3) "."counter(deci4) "."counter(deci5) ". "; } + .decimal6:before { transition: 0.5s;counter-increment: deci6; display: inline-block; margin-left: -2em; width: 6em; content: counter(deci1) "."counter(deci2) "."counter(deci3) "."counter(deci4) "."counter(deci5) "."counter(deci6) ". "; } + .decimal7:before { transition: 0.5s;counter-increment: deci7; display: inline-block; margin-left: -2em; width: 7em; content: counter(deci1) "."counter(deci2) "."counter(deci3) "."counter(deci4) "."counter(deci5) "."counter(deci6) "."counter(deci7) ". "; } + + .multi1:before { transition: 0.5s;counter-increment: multi1; display: inline-block; margin-left: -1em; width: 1.2em; content: counter(multi1, upper-alpha) ". "; } + .multi2:before { transition: 0.5s;counter-increment: multi2; display: inline-block; margin-left: -2em; width: 2em; content: counter(multi1, upper-alpha) "."counter(multi2, decimal) ". "; } + .multi3:before { transition: 0.5s;counter-increment: multi3; display: inline-block; margin-left: -2.85em; width:2.85em; content: counter(multi1, upper-alpha) "."counter(multi2, decimal) "."counter(multi3, lower-alpha) ". "; } + .multi4:before { transition: 0.5s;counter-increment: multi4; display: inline-block; margin-left: -4.2em; width: 4.2em; content: counter(multi1, upper-alpha) "."counter(multi2, decimal) "."counter(multi3, lower-alpha) "."counter(multi4, lower-roman) ". "; } + } +} diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.tsx b/src/client/views/nodes/formattedText/FormattedTextBox.tsx index cdf231985..fc63dfbf5 100644 --- a/src/client/views/nodes/formattedText/FormattedTextBox.tsx +++ b/src/client/views/nodes/formattedText/FormattedTextBox.tsx @@ -4,11 +4,11 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { isEqual } from "lodash"; import { action, computed, IReactionDisposer, Lambda, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; -import { baseKeymap } from "prosemirror-commands"; +import { baseKeymap, selectAll } from "prosemirror-commands"; import { history } from "prosemirror-history"; import { inputRules } from 'prosemirror-inputrules'; import { keymap } from "prosemirror-keymap"; -import { Fragment, Mark, Node, Slice } from "prosemirror-model"; +import { Fragment, Mark, Node, Slice, Schema } from "prosemirror-model"; import { EditorState, NodeSelection, Plugin, TextSelection, Transaction } from "prosemirror-state"; import { ReplaceStep } from 'prosemirror-transform'; import { EditorView } from "prosemirror-view"; @@ -16,13 +16,14 @@ import { DateField } from '../../../../fields/DateField'; import { DataSym, Doc, DocListCast, DocListCastAsync, Field, HeightSym, Opt, WidthSym, AclSym } from "../../../../fields/Doc"; import { documentSchema } from '../../../../fields/documentSchemas'; import applyDevTools = require("prosemirror-dev-tools"); +import { removeMarkWithAttrs } from "./prosemirrorPatches"; import { Id } from '../../../../fields/FieldSymbols'; import { InkTool } from '../../../../fields/InkField'; import { PrefetchProxy } from '../../../../fields/Proxy'; import { RichTextField } from "../../../../fields/RichTextField"; import { RichTextUtils } from '../../../../fields/RichTextUtils'; import { createSchema, makeInterface } from "../../../../fields/Schema"; -import { Cast, DateCast, NumCast, StrCast } from "../../../../fields/Types"; +import { Cast, DateCast, NumCast, StrCast, ScriptCast } from "../../../../fields/Types"; import { TraceMobx, OVERRIDE_ACL } from '../../../../fields/util'; import { addStyleSheet, addStyleSheetRule, clearStyleSheetRules, emptyFunction, numberRange, returnOne, returnZero, Utils, setupMoveUpEvents } from '../../../../Utils'; import { GoogleApiClientUtils, Pulls, Pushes } from '../../../apis/google_docs/GoogleApiClientUtils'; @@ -32,7 +33,7 @@ import { DocumentType } from '../../../documents/DocumentTypes'; import { DictationManager } from '../../../util/DictationManager'; import { DragManager } from "../../../util/DragManager"; import { makeTemplate } from '../../../util/DropConverter'; -import buildKeymap from "./ProsemirrorExampleTransfer"; +import buildKeymap, { updateBullets } from "./ProsemirrorExampleTransfer"; import RichTextMenu from './RichTextMenu'; import { RichTextRules } from "./RichTextRules"; @@ -56,8 +57,9 @@ import { DocumentButtonBar } from '../../DocumentButtonBar'; import { AudioBox } from '../AudioBox'; import { FieldView, FieldViewProps } from "../FieldView"; import "./FormattedTextBox.scss"; -import { FormattedTextBoxComment, formattedTextBoxCommentPlugin } from './FormattedTextBoxComment'; +import { FormattedTextBoxComment, formattedTextBoxCommentPlugin, findLinkMark } from './FormattedTextBoxComment'; import React = require("react"); +import { DocumentManager } from '../../../util/DocumentManager'; library.add(faEdit); library.add(faSmile, faTextHeight, faUpload); @@ -68,15 +70,10 @@ export interface FormattedTextBoxProps { xMargin?: number; // used to override document's settings for xMargin --- see CollectionCarouselView yMargin?: number; } - -const richTextSchema = createSchema({ - documentText: "string", -}); - export const GoogleRef = "googleDocId"; -type RichTextDocument = makeInterface<[typeof richTextSchema, typeof documentSchema]>; -const RichTextDocument = makeInterface(richTextSchema, documentSchema); +type RichTextDocument = makeInterface<[typeof documentSchema]>; +const RichTextDocument = makeInterface(documentSchema); type PullHandler = (exportState: Opt<GoogleApiClientUtils.Docs.ImportResult>, dataDoc: Doc) => void; @@ -86,14 +83,16 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp public static blankState = () => EditorState.create(FormattedTextBox.Instance.config); public static Instance: FormattedTextBox; public ProseRef?: HTMLDivElement; + public get EditorView() { return this._editorView; } private _ref: React.RefObject<HTMLDivElement> = React.createRef(); private _scrollRef: React.RefObject<HTMLDivElement> = React.createRef(); private _editorView: Opt<EditorView>; private _applyingChange: boolean = false; private _searchIndex = 0; + private _cachedLinks: Doc[] = []; private _undoTyping?: UndoManager.Batch; private _disposers: { [name: string]: IReactionDisposer } = {}; - private dropDisposer?: DragManager.DragDropDisposer; + private _dropDisposer?: DragManager.DragDropDisposer; @computed get _recording() { return this.dataDoc.audioState === "recording"; } set _recording(value) { this.dataDoc.audioState = value ? "recording" : undefined; } @@ -102,6 +101,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp public static FocusedBox: FormattedTextBox | undefined; public static SelectOnLoad = ""; + public static PasteOnLoad: ClipboardEvent | undefined; public static SelectOnLoadChar = ""; public static IsFragment(html: string) { return html.indexOf("data-pm-slice") !== -1; @@ -144,6 +144,33 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp public get CurrentDiv(): HTMLDivElement { return this._ref.current!; } + // removes all hyperlink anchors for the removed linkDoc + // TODO: bcz: Argh... if a section of text has multiple anchors, this should just remove the intended one. + // but since removing one anchor from the list of attr anchors isn't implemented, this will end up removing nothing. + public RemoveLinkFromDoc(linkDoc?: Doc) { + const state = this._editorView?.state; + if (state && linkDoc && this._editorView) { + var allLinks: any[] = []; + state.doc.nodesBetween(0, state.doc.nodeSize - 2, (node: any, pos: number, parent: any) => { + const foundMark = findLinkMark(node.marks); + const newHrefs = foundMark?.attrs.allLinks.filter((a: any) => a.href.includes(linkDoc[Id])) || []; + allLinks = newHrefs.length ? newHrefs : allLinks; + return true; + }); + if (allLinks.length) { + this._editorView.dispatch(removeMarkWithAttrs(state.tr, 0, state.doc.nodeSize - 2, state.schema.marks.linkAnchor, { allLinks })); + } + } + } + // removes all the specified link referneces from the selection. + // NOTE: as above, this won't work correctly if there are marks with overlapping but not exact sets of link references. + public RemoveLinkFromSelection(allLinks: { href: string, title: string, linkId: string, targetId: string }[]) { + const state = this._editorView?.state; + if (state && this._editorView) { + this._editorView.dispatch(removeMarkWithAttrs(state.tr, state.selection.from, state.selection.to, state.schema.marks.link, { allLinks })); + } + } + linkOnDeselect: Map<string, string> = new Map(); doLinkOnDeselect() { @@ -180,8 +207,8 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp this.linkOnDeselect.set(key, value); const id = Utils.GenerateDeterministicGuid(this.dataDoc[Id] + key); - const allHrefs = [{ href: Utils.prepend("/doc/" + id), title: value, targetId: id }]; - const link = this._editorView.state.schema.marks.link.create({ allHrefs, location: "onRight", title: value }); + const allLinks = [{ href: Utils.prepend("/doc/" + id), title: value, targetId: id }]; + const link = this._editorView.state.schema.marks.linkAnchor.create({ allLinks, location: "onRight", title: value }); const mval = this._editorView.state.schema.marks.metadataVal.create(); const offset = (tx.selection.to === range!.end - 1 ? -1 : 0); tx = tx.addMark(textEndSelection - value.length + offset, textEndSelection, link).addMark(textEndSelection - value.length + offset, textEndSelection, mval); @@ -202,13 +229,14 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp if (!this.dataDoc[AclSym]) { if (!this._applyingChange && json.replace(/"selection":.*/, "") !== curProto?.Data.replace(/"selection":.*/, "")) { this._applyingChange = true; - this.dataDoc[this.props.fieldKey + "-lastModified"] = new DateField(new Date(Date.now())); + (curText !== Cast(this.dataDoc[this.fieldKey], RichTextField)?.Text) && (this.dataDoc[this.props.fieldKey + "-lastModified"] = new DateField(new Date(Date.now()))); if ((!curTemp && !curProto) || curText || curLayout?.Data.includes("dash")) { // if no template, or there's text that didn't come from the layout template, write it to the document. (if this is driven by a template, then this overwrites the template text which is intended) if (json !== curLayout?.Data) { !curText && tx.storedMarks?.map(m => m.type.name === "pFontSize" && (Doc.UserDoc().fontSize = this.layoutDoc._fontSize = m.attrs.fontSize)); !curText && tx.storedMarks?.map(m => m.type.name === "pFontFamily" && (Doc.UserDoc().fontFamily = this.layoutDoc._fontFamily = m.attrs.fontFamily)); this.dataDoc[this.props.fieldKey] = new RichTextField(json, curText); this.dataDoc[this.props.fieldKey + "-noTemplate"] = (curTemp?.Text || "") !== curText; // mark the data field as being split from the template if it has been edited + ScriptCast(this.layoutDoc.onTextChanged, null)?.script.run({ this: this.layoutDoc, self: this.rootDoc, text: curText }); } } else { // if we've deleted all the text in a note driven by a template, then restore the template data this.dataDoc[this.props.fieldKey] = undefined; @@ -248,8 +276,8 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp const lastSel = Math.min(flattened.length - 1, this._searchIndex); this._searchIndex = ++this._searchIndex > flattened.length - 1 ? 0 : this._searchIndex; const alink = DocUtils.MakeLink({ doc: this.rootDoc }, { doc: target }, "automatic")!; - const allHrefs = [{ href: Utils.prepend("/doc/" + alink[Id]), title: "a link", targetId: target[Id], linkId: alink[Id] }]; - const link = this._editorView.state.schema.marks.link.create({ allHrefs, title: "a link", location }); + const allLinks = [{ href: Utils.prepend("/doc/" + alink[Id]), title: "a link", targetId: target[Id], linkId: alink[Id] }]; + const link = this._editorView.state.schema.marks.linkAnchor.create({ allLinks, title: "a link", location }); this._editorView.dispatch(tr.addMark(flattened[lastSel].from, flattened[lastSel].to, link)); } } @@ -269,12 +297,19 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp } public unhighlightSearchTerms = () => { - if (this._editorView && (this._editorView as any).docView) { + if (window.screen.width < 600) null; + else if (this._editorView && (this._editorView as any).docView) { const mark = this._editorView.state.schema.mark(this._editorView.state.schema.marks.search_highlight); const activeMark = this._editorView.state.schema.mark(this._editorView.state.schema.marks.search_highlight, { selected: true }); const end = this._editorView.state.doc.nodeSize - 2; this._editorView.dispatch(this._editorView.state.tr.removeMark(0, end, mark).removeMark(0, end, activeMark)); } + if (FormattedTextBox.PasteOnLoad) { + const pdfDocId = FormattedTextBox.PasteOnLoad.clipboardData?.getData("dash/pdfOrigin"); + const pdfRegionId = FormattedTextBox.PasteOnLoad.clipboardData?.getData("dash/pdfRegion"); + FormattedTextBox.PasteOnLoad = undefined; + setTimeout(() => pdfDocId && pdfRegionId && this.addPdfReference(pdfDocId, pdfRegionId, undefined), 10); + } } adoptAnnotation = (start: number, end: number, mark: Mark) => { const view = this._editorView!; @@ -283,8 +318,8 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp } protected createDropTarget = (ele: HTMLDivElement) => { this.ProseRef = ele; - this.dropDisposer?.(); - ele && (this.dropDisposer = DragManager.MakeDropTarget(ele, this.drop.bind(this), this.layoutDoc)); + this._dropDisposer?.(); + ele && (this._dropDisposer = DragManager.MakeDropTarget(ele, this.drop.bind(this), this.layoutDoc)); } @undoBatch @@ -610,9 +645,9 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp 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({ allHrefs, title, location, linkId }); + const allLinks = [{ href, title, targetId, linkId }]; + allLinks.push(...(node.marks.find((m: Mark) => m.type.name === schema.marks.linkAnchor.name)?.attrs.allLinks ?? [])); + const link = state.schema.marks.linkAnchor.create({ allLinks, title, location, linkId }); tr = tr.addMark(pos, pos + node.nodeSize, link); } }); @@ -622,6 +657,12 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp } } componentDidMount() { + this._cachedLinks = DocListCast(this.Document.links); + this._disposers.links = reaction(() => DocListCast(this.Document.links), // if a link is deleted, then remove all hyperlinks that reference it from the text's marks + newLinks => { + this._cachedLinks.forEach(l => !newLinks.includes(l) && this.RemoveLinkFromDoc(l)); + this._cachedLinks = newLinks; + }); this._disposers.buttonBar = reaction( () => DocumentButtonBar.Instance, instance => { @@ -652,8 +693,10 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp incomingValue => { if (incomingValue !== undefined && this._editorView && !this._applyingChange) { const updatedState = JSON.parse(incomingValue); - this._editorView.updateState(EditorState.fromJSON(this.config, updatedState)); - this.tryUpdateHeight(); + if (JSON.stringify(this._editorView.state.toJSON()) !== JSON.stringify(updatedState)) { + this._editorView.updateState(EditorState.fromJSON(this.config, updatedState)); + this.tryUpdateHeight(); + } } } ); @@ -725,8 +768,8 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp return node.copy(content.frag); } const marks = [...node.marks]; - const linkIndex = marks.findIndex(mark => mark.type === editor.state.schema.marks.link); - return linkIndex !== -1 && marks[linkIndex].attrs.allRefs.find((item: { href: string }) => scrollToLinkID === item.href.replace(/.*\/doc\//, "")) ? node : undefined; + const linkIndex = marks.findIndex(mark => mark.type === editor.state.schema.marks.linkAnchor); + return linkIndex !== -1 && marks[linkIndex].attrs.allLinks.find((item: { href: string }) => scrollToLinkID === item.href.replace(/.*\/doc\//, "")) ? node : undefined; }; let start = 0; @@ -857,8 +900,13 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp handlePaste = (view: EditorView, event: Event, slice: Slice): boolean => { const cbe = event as ClipboardEvent; - const pdfDocId = cbe.clipboardData && cbe.clipboardData.getData("dash/pdfOrigin"); - const pdfRegionId = cbe.clipboardData && cbe.clipboardData.getData("dash/pdfRegion"); + const pdfDocId = cbe.clipboardData?.getData("dash/pdfOrigin"); + const pdfRegionId = cbe.clipboardData?.getData("dash/pdfRegion"); + return pdfDocId && pdfRegionId && this.addPdfReference(pdfDocId, pdfRegionId, slice) ? true : false; + } + + addPdfReference = (pdfDocId: string, pdfRegionId: string, slice?: Slice) => { + const view = this._editorView!; if (pdfDocId && pdfRegionId) { DocServer.GetRefField(pdfDocId).then(pdfDoc => { DocServer.GetRefField(pdfRegionId).then(pdfRegion => { @@ -866,17 +914,22 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp setTimeout(async () => { const targetField = Doc.LayoutFieldKey(pdfDoc); const targetAnnotations = await DocListCastAsync(pdfDoc[DataSym][targetField + "-annotations"]);// bcz: better to have the PDF's view handle updating its own annotations - targetAnnotations?.push(pdfRegion); + if (targetAnnotations) targetAnnotations.push(pdfRegion); + else Doc.AddDocToList(pdfDoc[DataSym], targetField + "-annotations", pdfRegion); }); const link = DocUtils.MakeLink({ doc: this.rootDoc }, { doc: pdfRegion }, "PDF pasted"); if (link) { - cbe.clipboardData!.setData("dash/linkDoc", link[Id]); const linkId = link[Id]; - const frag = addMarkToFrag(slice.content, (node: Node) => addLinkMark(node, StrCast(pdfDoc.title), linkId)); - slice = new Slice(frag, slice.openStart, slice.openEnd); - const tr = view.state.tr.replaceSelection(slice); - view.dispatch(tr.scrollIntoView().setMeta("paste", true).setMeta("uiEvent", "paste")); + const quote = view.state.schema.nodes.blockquote.create(); + quote.content = addMarkToFrag(slice?.content || view.state.doc.content, (node: Node) => addLinkMark(node, StrCast(pdfDoc.title), linkId)); + const newSlice = new Slice(Fragment.from(quote), slice?.openStart || 0, slice?.openEnd || 0); + if (slice) { + view.dispatch(view.state.tr.replaceSelection(newSlice).scrollIntoView().setMeta("paste", true).setMeta("uiEvent", "paste")); + } else { + selectAll(view.state, (tx: Transaction) => view.dispatch(tx.replaceSelection(newSlice).scrollIntoView())); + + } } } }); @@ -898,7 +951,8 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp } const marks = [...node.marks]; const linkIndex = marks.findIndex(mark => mark.type.name === "link"); - const link = view.state.schema.mark(view.state.schema.marks.link, { href: Utils.prepend(`/doc/${linkId}`), location: "onRight", title: title, docref: true }); + const allLinks = [{ href: Utils.prepend(`/doc/${linkId}`), title, linkId }]; + const link = view.state.schema.mark(view.state.schema.marks.linkAnchor, { allLinks, location: "onRight", title, docref: true }); marks.splice(linkIndex === -1 ? 0 : linkIndex, 1, link); return node.mark(marks); } @@ -933,7 +987,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp clipboardTextSerializer: this.clipboardTextSerializer, handlePaste: this.handlePaste, }); - //applyDevTools.applyDevTools(this._editorView); + !Doc.UserDoc().noviceMode && applyDevTools.applyDevTools(this._editorView); const startupText = !rtfField && this._editorView && Field.toString(this.dataDoc[fieldKey] as Field); if (startupText) { const { state: { tr }, dispatch } = this._editorView; @@ -952,7 +1006,9 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp } (selectOnLoad /* || !rtfField?.Text*/) && this._editorView!.focus(); // add user mark for any first character that was typed since the user mark that gets set in KeyPress won't have been called yet. - this._editorView!.state.storedMarks = [...(this._editorView!.state.storedMarks ? this._editorView!.state.storedMarks : []), schema.marks.user_mark.create({ userid: Doc.CurrentUserEmail, modified: Math.floor(Date.now() / 1000) })]; + if (!this._editorView!.state.storedMarks || !this._editorView!.state.storedMarks.some(mark => mark.type === schema.marks.user_mark)) { + this._editorView!.state.storedMarks = [...(this._editorView!.state.storedMarks ? this._editorView!.state.storedMarks : []), schema.marks.user_mark.create({ userid: Doc.CurrentUserEmail, modified: Math.floor(Date.now() / 1000) })]; + } } getFont(font: string) { switch (font) { @@ -976,6 +1032,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp _downX = 0; _downY = 0; _break = false; + _collapsed = false; onPointerDown = (e: React.PointerEvent): void => { if (this._recording && !e.ctrlKey && e.button === 0) { this.stopDictation(true); @@ -1013,9 +1070,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp const editor = this._editorView!; FormattedTextBoxComment.textBox = this; const pcords = editor.posAtCoords({ left: e.clientX, top: e.clientY }); - const node = pcords && editor.state.doc.nodeAt(pcords.pos); // get what prosemirror thinks the clicked node is (if it's null, then we didn't click on any text) - !this.props.isSelected(true) && editor.dispatch(editor.state.tr.setSelection(node && pcords ? - new NodeSelection(editor.state.doc.resolve(pcords.pos)) : new TextSelection(editor.state.doc.resolve(pcords?.pos || 0)))); + !this.props.isSelected(true) && editor.dispatch(editor.state.tr.setSelection(new TextSelection(editor.state.doc.resolve(pcords?.pos || 0)))); FormattedTextBoxComment.update(editor, undefined, (e.target as any)?.className === "prosemirror-dropdownlink" ? (e.target as any).href : ""); } (e.nativeEvent as any).formattedHandled = true; @@ -1026,6 +1081,40 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp } @action + onDoubleClick = (e: React.MouseEvent): void => { + + this.doLinkOnDeselect(); + FormattedTextBox._downEvent = true; + FormattedTextBoxComment.textBox = this; + if (this.props.onClick && e.button === 0 && !this.props.isSelected(false)) { + e.preventDefault(); + } + if (e.button === 0 && this.props.isSelected(true) && !e.altKey && !e.ctrlKey && !e.metaKey) { + if (e.clientX < this.ProseRef!.getBoundingClientRect().right) { // stop propagation if not in sidebar + e.stopPropagation(); // if the text box is selected, then it consumes all down events + } + } + if (e.button === 2 || (e.button === 0 && e.ctrlKey)) { + e.preventDefault(); + } + FormattedTextBoxComment.Hide(); + if (FormattedTextBoxComment.linkDoc) { + if (FormattedTextBoxComment.linkDoc.type !== DocumentType.LINK) { + this.props.addDocTab(FormattedTextBoxComment.linkDoc, e.ctrlKey ? "inTab" : "onRight"); + } else { + DocumentManager.Instance.FollowLink(FormattedTextBoxComment.linkDoc, this.props.Document, + (doc: Doc, followLinkLocation: string) => this.props.addDocTab(doc, e.ctrlKey ? "inTab" : followLinkLocation)); + } + } + + (e.nativeEvent as any).formattedHandled = true; + + if (e.buttons === 1 && this.props.isSelected(true) && !e.altKey) { + e.stopPropagation(); + } + } + + @action onFocused = (e: React.FocusEvent): void => { FormattedTextBox.FocusedBox = this; this.tryUpdateHeight(); @@ -1058,9 +1147,14 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp static _bulletStyleSheet: any = addStyleSheet(); static _userStyleSheet: any = addStyleSheet(); - + _forceUncollapse = true; // if the cursor doesn't move between clicks, then the selection will disappear for some reason. This flags the 2nd click as happening on a selection which allows bullet points to toggle + _forceDownNode: Node | undefined; onClick = (e: React.MouseEvent): void => { - if ((this._editorView!.root as any).getSelection().isCollapsed) { // this is a hack to allow the cursor to be placed at the end of a document when the document ends in an inline dash comment. Apparently Chrome on Windows has a bug/feature which breaks this when clicking after the end of the text. + if (Math.abs(e.clientX - this._downX) > 4 || Math.abs(e.clientY - this._downY) > 4) { + this._forceDownNode = undefined; + return; + } + if (!this._forceUncollapse || (this._editorView!.root as any).getSelection().isCollapsed) { // this is a hack to allow the cursor to be placed at the end of a document when the document ends in an inline dash comment. Apparently Chrome on Windows has a bug/feature which breaks this when clicking after the end of the text. const pcords = this._editorView!.posAtCoords({ left: e.clientX, top: e.clientY }); const node = pcords && this._editorView!.state.doc.nodeAt(pcords.pos); // get what prosemirror thinks the clicked node is (if it's null, then we didn't click on any text) if (pcords && node?.type === this._editorView!.state.schema.nodes.dashComment) { @@ -1072,6 +1166,9 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp if (e.clientY > lastNode?.getBoundingClientRect().bottom) { // if we clicked below the last prosemirror div, then set the selection to be the end of the document this._editorView!.dispatch(this._editorView!.state.tr.setSelection(TextSelection.create(this._editorView!.state.doc, this._editorView!.state.doc.content.size))); } + } else if ([this._editorView!.state.schema.nodes.ordered_list, this._editorView!.state.schema.nodes.listItem].includes(node?.type) && + node !== (this._editorView!.state.selection as NodeSelection)?.node && pcords) { + this._editorView!.dispatch(this._editorView!.state.tr.setSelection(NodeSelection.create(this._editorView!.state.doc, pcords.pos!))); } } if ((e.nativeEvent as any).formattedHandled) { e.stopPropagation(); return; } @@ -1079,12 +1176,15 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp if (this.props.isSelected(true)) { // if text box is selected, then it consumes all click events e.stopPropagation(); - this.hitBulletTargets(e.clientX, e.clientY, e.shiftKey, false); + this.hitBulletTargets(e.clientX, e.clientY, !this._editorView?.state.selection.empty || this._forceUncollapse, false, this._forceDownNode, e.shiftKey); } + this._forceUncollapse = !(this._editorView!.root as any).getSelection().isCollapsed; + this._forceDownNode = (this._editorView!.state.selection as NodeSelection)?.node; } // this hackiness handles clicking on the list item bullets to do expand/collapse. the bullets are ::before pseudo elements so there's no real way to hit test against them. - hitBulletTargets(x: number, y: number, collapse: boolean, highlightOnly: boolean) { + hitBulletTargets(x: number, y: number, collapse: boolean, highlightOnly: boolean, downNode: Node | undefined = undefined, selectOrderedList: boolean = false) { + this._forceUncollapse = false; clearStyleSheetRules(FormattedTextBox._bulletStyleSheet); const clickPos = this._editorView!.posAtCoords({ left: x, top: y }); let olistPos = clickPos?.pos; @@ -1100,20 +1200,18 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp $olistPos = this._editorView?.state.doc.resolve(($olistPos as any).path[($olistPos as any).path.length - 4]); } } + const listPos = this._editorView?.state.doc.resolve(clickPos.pos); const listNode = this._editorView?.state.doc.nodeAt(clickPos.pos); - if (olistNode && olistNode.type === this._editorView?.state.schema.nodes.ordered_list) { - if (!collapse) { - if (!highlightOnly) { - this._editorView.dispatch(this._editorView.state.tr.setSelection(new NodeSelection($olistPos!))); - } - addStyleSheetRule(FormattedTextBox._bulletStyleSheet, olistNode.attrs.mapStyle + olistNode.attrs.bulletStyle + ":hover:before", { background: "lightgray" }); - } else if (listNode && listNode.type === this._editorView.state.schema.nodes.list_item) { - if (!highlightOnly) { + if (olistNode && olistNode.type === this._editorView?.state.schema.nodes.ordered_list && listNode) { + if (!highlightOnly) { + if (selectOrderedList || (!collapse && listNode.attrs.visibility)) { + this._editorView.dispatch(this._editorView.state.tr.setSelection(new NodeSelection(selectOrderedList ? $olistPos! : listPos!))); + } else if (!listNode.attrs.visibility || downNode === listNode) { this._editorView.dispatch(this._editorView.state.tr.setNodeMarkup(clickPos.pos, listNode.type, { ...listNode.attrs, visibility: !listNode.attrs.visibility })); this._editorView.dispatch(this._editorView.state.tr.setSelection(TextSelection.create(this._editorView.state.doc, clickPos.pos))); } - addStyleSheetRule(FormattedTextBox._bulletStyleSheet, olistNode.attrs.mapStyle + olistNode.attrs.bulletStyle + ":hover:before", { background: "lightgray" }); } + addStyleSheetRule(FormattedTextBox._bulletStyleSheet, olistNode.attrs.mapStyle + olistNode.attrs.bulletStyle + ":hover:before", { background: "lightgray" }); } } } @@ -1121,7 +1219,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp e.stopPropagation(); const view = this._editorView as any; - // this interposes on prosemirror's upHandler to prevent prosemirror's up from invoked multiple times when there + // this interposes on prosemirror's upHandler to prevent prosemirror's up from invoked multiple times when there // are nested prosemirrors. We only want the lowest level prosemirror to be invoked. if (view.mouseDown) { const originalUpHandler = view.mouseDown.up; @@ -1144,18 +1242,27 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp }); } - public static HadSelection: boolean = false; - onBlur = (e: any) => { - FormattedTextBox.HadSelection = window.getSelection()?.toString() !== ""; - //DictationManager.Controls.stop(false); + public startUndoTypingBatch() { + this._undoTyping = UndoManager.StartBatch("undoTyping"); + } + + public endUndoTypingBatch() { + const wasUndoing = this._undoTyping; if (this._undoTyping) { this._undoTyping.end(); this._undoTyping = undefined; } + return wasUndoing; + } + public static HadSelection: boolean = false; + onBlur = (e: any) => { + FormattedTextBox.HadSelection = window.getSelection()?.toString() !== ""; + //DictationManager.Controls.stop(false); + this.endUndoTypingBatch(); this.doLinkOnDeselect(); // move the richtextmenu offscreen - if (!RichTextMenu.Instance.Pinned && !RichTextMenu.Instance.overMenu) RichTextMenu.Instance.jumpTo(-300, -300); + if (!RichTextMenu.Instance.Pinned) RichTextMenu.Instance.delayHide(); } _lastTimedMark: Mark | undefined = undefined; @@ -1189,10 +1296,14 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp // this._editorView!.dispatch(this._editorView!.state.tr.removeStoredMark(schema.marks.user_mark.create({})).addStoredMark(mark)); if (!this._undoTyping) { - this._undoTyping = UndoManager.StartBatch("undoTyping"); + this.startUndoTypingBatch(); } } + ondrop = (eve: React.DragEvent) => { + this._editorView!.dispatch(updateBullets(this._editorView!.state.tr, this._editorView!.state.schema)); + eve.stopPropagation(); // drag n drop of text within text note will generate a new note if not caughst, as will dragging in from outside of Dash. + } onscrolled = (ev: React.UIEvent) => { this.layoutDoc._scrollTop = this._scrollRef.current!.scrollTop; } @@ -1200,13 +1311,13 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp tryUpdateHeight(limitHeight?: number) { let scrollHeight = this._ref.current?.scrollHeight; if (this.props.renderDepth && this.layoutDoc._autoHeight && !this.props.ignoreAutoHeight && scrollHeight) { // if top === 0, then the text box is growing upward (as the overlay caption) which doesn't contribute to the height computation - scrollHeight = scrollHeight * NumCast(this.layoutDoc.scale, 1); + scrollHeight = scrollHeight * NumCast(this.layoutDoc._viewScale, 1); if (limitHeight && scrollHeight > limitHeight) { scrollHeight = limitHeight; this.layoutDoc.limitHeight = undefined; this.layoutDoc._autoHeight = false; } - const nh = this.layoutDoc.isTemplateForField ? 0 : NumCast(this.dataDoc._nativeHeight, 0); + const nh = this.layoutDoc.isTemplateForField ? 0 : NumCast(this.layoutDoc._nativeHeight, 0); const dh = NumCast(this.rootDoc._height, 0); const newHeight = Math.max(10, (nh ? dh / nh * scrollHeight : scrollHeight) + (this.props.ChromeHeight ? this.props.ChromeHeight() : 0)); if (this.rootDoc !== this.layoutDoc.doc && !this.layoutDoc.resolvedDataDoc) { @@ -1214,11 +1325,11 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp console.log("Delayed height adjustment..."); setTimeout(() => { this.rootDoc._height = newHeight; - this.dataDoc._nativeHeight = nh ? scrollHeight : undefined; + this.layoutDoc._nativeHeight = nh ? scrollHeight : undefined; }, 10); } else { - this.rootDoc._height = newHeight; - this.dataDoc._nativeHeight = nh ? scrollHeight : undefined; + this.layoutDoc._height = newHeight; + this.layoutDoc._nativeHeight = nh ? scrollHeight : undefined; } } } @@ -1229,7 +1340,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp @computed get sidebarColor() { return StrCast(this.layoutDoc[this.props.fieldKey + "-backgroundColor"], StrCast(this.layoutDoc[this.props.fieldKey + "-backgroundColor"], "transparent")); } render() { TraceMobx(); - const scale = this.props.ContentScaling() * NumCast(this.layoutDoc.scale, 1); + const scale = this.props.ContentScaling() * NumCast(this.layoutDoc._viewScale, 1); const rounded = StrCast(this.layoutDoc.borderRounding) === "100%" ? "-rounded" : ""; const interactive = Doc.GetSelectedTool() === InkTool.None && !this.layoutDoc.isBackground; if (this.props.isSelected()) { @@ -1258,7 +1369,8 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp color: this.props.color ? this.props.color : StrCast(this.layoutDoc[this.props.fieldKey + "-color"], this.props.hideOnLeave ? "white" : "inherit"), pointerEvents: interactive ? undefined : "none", fontSize: Cast(this.layoutDoc._fontSize, "number", null), - fontFamily: StrCast(this.layoutDoc._fontFamily, "inherit") + fontFamily: StrCast(this.layoutDoc._fontFamily, "inherit"), + transition: "opacity 1s" }} onContextMenu={this.specificContextMenu} onKeyDown={this.onKeyPress} @@ -1280,11 +1392,14 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp } } })} + onDoubleClick={this.onDoubleClick} > - <div className={`formattedTextBox-outer`} style={{ width: `calc(100% - ${this.sidebarWidthPercent})`, pointerEvents: !this.props.isSelected() ? "none" : undefined }} onScroll={this.onscrolled} ref={this._scrollRef}> + <div className={`formattedTextBox-outer`} ref={this._scrollRef} + style={{ width: `calc(100% - ${this.sidebarWidthPercent})`, pointerEvents: !this.props.isSelected() ? "none" : undefined }} + onScroll={this.onscrolled} onDrop={this.ondrop} > <div className={`formattedTextBox-inner${rounded}${selclass}`} ref={this.createDropTarget} style={{ - padding: `${Math.max(0, NumCast(this.layoutDoc._yMargin, this.props.yMargin || 0) + selPad)}px ${NumCast(this.layoutDoc._xMargin, this.props.xMargin || 0) + selPad}px`, + padding: this.layoutDoc._textBoxPadding ? StrCast(this.layoutDoc._textBoxPadding) : `${Math.max(0, NumCast(this.layoutDoc._yMargin, this.props.yMargin || 0) + selPad)}px ${NumCast(this.layoutDoc._xMargin, this.props.xMargin || 0) + selPad}px`, pointerEvents: !this.props.isSelected() ? ((this.layoutDoc.isLinkButton || this.props.onClick) ? "none" : "all") : undefined }} /> @@ -1324,7 +1439,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp setTimeout(() => this._editorView!.focus(), 500); e.stopPropagation(); }} > - <FontAwesomeIcon className="formattedTExtBox-audioFont" + <FontAwesomeIcon className="formattedTextBox-audioFont" style={{ color: this._recording ? "red" : "blue", opacity: this._recording ? 1 : 0.5, display: this.props.isSelected() ? "" : "none" }} icon={"microphone"} size="sm" /> </div>} </div> diff --git a/src/client/views/nodes/formattedText/FormattedTextBoxComment.scss b/src/client/views/nodes/formattedText/FormattedTextBoxComment.scss index 2dd63ec21..9089e7039 100644 --- a/src/client/views/nodes/formattedText/FormattedTextBoxComment.scss +++ b/src/client/views/nodes/formattedText/FormattedTextBoxComment.scss @@ -8,10 +8,12 @@ margin-bottom: 7px; -webkit-transform: translateX(-50%); transform: translateX(-50%); - } - .FormattedTextBox-tooltip:before { +} + +.FormattedTextBox-tooltip:before { content: ""; - height: 0; width: 0; + height: 0; + width: 0; position: absolute; left: 50%; margin-left: -5px; @@ -19,10 +21,12 @@ border: 5px solid transparent; border-bottom-width: 0; border-top-color: silver; - } - .FormattedTextBox-tooltip:after { +} + +.FormattedTextBox-tooltip:after { content: ""; - height: 0; width: 0; + height: 0; + width: 0; position: absolute; left: 50%; margin-left: -5px; @@ -30,4 +34,72 @@ border: 5px solid transparent; border-bottom-width: 0; border-top-color: white; - }
\ No newline at end of file +} + +.FormattedTextBoxComment-buttons { + display: none; + position: absolute; + top: 50%; + right: 0; + transform: translateY(-50%); + + .FormattedTextBoxComment-button { + width: 20px; + height: 20px; + margin: 0; + margin-right: 6px; + border-radius: 50%; + pointer-events: auto; + background-color: rgb(38, 40, 41); + color: rgb(178, 181, 184); + font-size: 65%; + transition: transform 0.2s; + text-align: center; + position: relative; + + // margin-top: "auto"; + // margin-bottom: "auto"; + // background: black; + // color: white; + // display: inline-block; + // border-radius: 18px; + // font-size: 12.5px; + // width: 18px; + // height: 18px; + // margin-top: auto; + // margin-bottom: auto; + // margin-right: 3px; + // cursor: pointer; + // transition: transform 0.2s; + + .FormattedTextBoxComment-fa-icon { + margin-top: "auto"; + margin-bottom: "auto"; + background: black; + color: white; + display: inline-block; + border-radius: 18px; + font-size: 12.5px; + width: 18px; + height: 18px; + margin-top: auto; + margin-bottom: auto; + margin-right: 3px; + cursor: pointer; + transition: transform 0.2s; + // position: absolute; + // top: 50%; + // left: 50%; + // transform: translate(-50%, -50%); + } + + &:last-child { + margin-right: 0; + } + + &:hover { + background: rgb(53, 146, 199); + ; + } + } +}
\ No newline at end of file diff --git a/src/client/views/nodes/formattedText/FormattedTextBoxComment.tsx b/src/client/views/nodes/formattedText/FormattedTextBoxComment.tsx index 0d8e22251..56826e5c7 100644 --- a/src/client/views/nodes/formattedText/FormattedTextBoxComment.tsx +++ b/src/client/views/nodes/formattedText/FormattedTextBoxComment.tsx @@ -2,7 +2,7 @@ import { Mark, ResolvedPos } from "prosemirror-model"; import { EditorState, Plugin } from "prosemirror-state"; import { EditorView } from "prosemirror-view"; import * as ReactDOM from 'react-dom'; -import { Doc, DocCastAsync } from "../../../../fields/Doc"; +import { Doc, DocCastAsync, Opt } from "../../../../fields/Doc"; import { Cast, FieldValue, NumCast } from "../../../../fields/Types"; import { emptyFunction, returnEmptyString, returnFalse, Utils, emptyPath, returnZero, returnOne, returnEmptyFilter } from "../../../../Utils"; import { DocServer } from "../../../DocServer"; @@ -16,6 +16,11 @@ import React = require("react"); import { Docs } from "../../../documents/Documents"; import wiki from "wikijs"; import { DocumentType } from "../../../documents/DocumentTypes"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { action } from "mobx"; +import { LinkManager } from "../../../util/LinkManager"; +import { LinkDocPreview } from "../LinkDocPreview"; +import { DocumentLinksButton } from "../DocumentLinksButton"; export let formattedTextBoxCommentPlugin = new Plugin({ view(editorView) { return new FormattedTextBoxComment(editorView); } @@ -27,7 +32,7 @@ export function findUserMark(marks: Mark[]): Mark | undefined { return marks.find(m => m.attrs.userid); } export function findLinkMark(marks: Mark[]): Mark | undefined { - return marks.find(m => m.type === schema.marks.link); + return marks.find(m => m.type === schema.marks.linkAnchor); } export function findStartOfMark(rpos: ResolvedPos, view: EditorView, finder: (marks: Mark[]) => Mark | undefined) { let before = 0; @@ -62,6 +67,10 @@ export class FormattedTextBoxComment { static mark: Mark; static textBox: FormattedTextBox | undefined; static linkDoc: Doc | undefined; + + static _deleteRef: Opt<HTMLDivElement | null>; + static _followRef: Opt<HTMLDivElement | null>; + constructor(view: any) { if (!FormattedTextBoxComment.tooltip) { const root = document.getElementById("root"); @@ -75,8 +84,8 @@ export class FormattedTextBoxComment { FormattedTextBoxComment.tooltip.appendChild(FormattedTextBoxComment.tooltipText); FormattedTextBoxComment.tooltip.className = "FormattedTextBox-tooltip"; FormattedTextBoxComment.tooltip.style.pointerEvents = "all"; - FormattedTextBoxComment.tooltip.style.maxWidth = "350px"; - FormattedTextBoxComment.tooltip.style.maxHeight = "250px"; + FormattedTextBoxComment.tooltip.style.maxWidth = "200px"; + FormattedTextBoxComment.tooltip.style.maxHeight = "206px"; FormattedTextBoxComment.tooltip.style.width = "100%"; FormattedTextBoxComment.tooltip.style.height = "100%"; FormattedTextBoxComment.tooltip.style.overflow = "hidden"; @@ -87,12 +96,25 @@ export class FormattedTextBoxComment { const textBox = FormattedTextBoxComment.textBox; if (FormattedTextBoxComment.linkDoc && !keep && textBox) { if (FormattedTextBoxComment.linkDoc.author) { - if (FormattedTextBoxComment.linkDoc.type !== DocumentType.LINK) { - textBox.props.addDocTab(FormattedTextBoxComment.linkDoc, e.ctrlKey ? "inTab" : "onRight"); + + if (FormattedTextBoxComment._deleteRef && FormattedTextBoxComment._deleteRef.contains(e.target as any)) { + this.deleteLink(); + } else if (FormattedTextBoxComment._followRef && FormattedTextBoxComment._followRef.contains(e.target as any)) { + 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 { - DocumentManager.Instance.FollowLink(FormattedTextBoxComment.linkDoc, textBox.props.Document, - (doc: Doc, followLinkLocation: string) => textBox.props.addDocTab(doc, e.ctrlKey ? "inTab" : followLinkLocation)); + 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"); @@ -106,6 +128,15 @@ export class FormattedTextBoxComment { } } + @action + deleteLink = () => { + FormattedTextBoxComment.linkDoc ? LinkManager.Instance.deleteLink(FormattedTextBoxComment.linkDoc) : null; + LinkDocPreview.LinkInfo = undefined; + DocumentLinksButton.EditLink = undefined; + //FormattedTextBoxComment.tooltipText = undefined; + FormattedTextBoxComment.Hide(); + } + public static Hide() { FormattedTextBoxComment.textBox = undefined; FormattedTextBoxComment.tooltip && (FormattedTextBoxComment.tooltip.style.display = "none"); @@ -177,11 +208,12 @@ export class FormattedTextBoxComment { // this checks if the selection is a hyperlink. If so, it displays the target doc's text for internal links, and the url of the target for external links. if (set === "none" && state.selection.$from) { nbef = findStartOfMark(state.selection.$from, view, findLinkMark); - const naft = findEndOfMark(state.selection.$from, view, findLinkMark); + const naft = findEndOfMark(state.selection.$from, view, findLinkMark) || nbef; 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); - const href = mark?.attrs.allHrefs.find((item: { href: string }) => item.href)?.href || forceUrl; + child = child || (nbef && state.selection.$from.nodeBefore); + const mark = child ? findLinkMark(child.marks) : undefined; + const href = (!mark?.attrs.docref || naft === nbef) && mark?.attrs.allLinks.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; @@ -209,32 +241,87 @@ export class FormattedTextBoxComment { } if (target?.author) { FormattedTextBoxComment.showCommentbox("", view, nbef); - ReactDOM.render(<ContentFittingDocumentView - Document={target} - LibraryPath={emptyPath} - fitToBox={true} - moveDocument={returnFalse} - rootSelected={returnFalse} - ScreenToLocalTransform={Transform.Identity} - parentActive={returnFalse} - addDocument={returnFalse} - removeDocument={returnFalse} - addDocTab={returnFalse} - pinToPres={returnFalse} - dontRegisterView={true} - docFilters={returnEmptyFilter} - ContainingCollectionDoc={undefined} - ContainingCollectionView={undefined} - renderDepth={0} - PanelWidth={() => Math.min(350, NumCast(target._width, 350))} - PanelHeight={() => Math.min(250, NumCast(target._height, 250))} - focus={emptyFunction} - whenActiveChanged={returnFalse} - bringToFront={returnFalse} - ContentScaling={returnOne} - NativeWidth={returnZero} - NativeHeight={returnZero} - />, FormattedTextBoxComment.tooltipText); + const docPreview = <div style={{ backgroundColor: "white", border: "8px solid white" }}> + {target.title} + <div className="wrapper" style={{ float: "right" }}> + <div title="Delete link" className="FormattedTextBoxComment-button" style={{ + display: "inline", + paddingLeft: "6px", + paddingRight: "6px", + paddingTop: "2.5px", + paddingBottom: "2.5px", + width: "20px", + height: "20px", + margin: 0, + marginRight: "6px", + borderRadius: "50%", + pointerEvents: "auto", + backgroundColor: "rgb(38, 40, 41)", + color: "rgb(178, 181, 184)", + transition: "transform 0.2s", + textAlign: "center", + position: "relative" + }} ref={(r) => this._deleteRef = r}> + <FontAwesomeIcon className="FormattedTextBox-fa-icon" icon="trash" + size="sm" /></div> + <div title="Follow link" className="FormattedTextBoxComment-button" style={{ + display: "inline", + paddingLeft: "6px", + paddingRight: "6px", + paddingTop: "2.5px", + paddingBottom: "2.5px", + width: "20px", + height: "20px", + margin: 0, + marginRight: "6px", + borderRadius: "50%", + pointerEvents: "auto", + backgroundColor: "rgb(38, 40, 41)", + color: "rgb(178, 181, 184)", + transition: "transform 0.2s", + textAlign: "center", + position: "relative" + }} ref={(r) => this._followRef = r}> + <FontAwesomeIcon className="FormattedTextBox-fa-icon" icon="arrow-right" + size="sm" /> + </div> + </div> + <div className="wrapper" style={{ + maxWidth: "180px", maxHeight: "168px", overflow: "hidden", + overflowY: "hidden", paddingTop: "5px" + }}> + <ContentFittingDocumentView + Document={target} + LibraryPath={emptyPath} + fitToBox={true} + moveDocument={returnFalse} + rootSelected={returnFalse} + ScreenToLocalTransform={Transform.Identity} + parentActive={returnFalse} + addDocument={returnFalse} + removeDocument={returnFalse} + addDocTab={returnFalse} + pinToPres={returnFalse} + dontRegisterView={true} + docFilters={returnEmptyFilter} + ContainingCollectionDoc={undefined} + ContainingCollectionView={undefined} + renderDepth={0} + PanelWidth={() => Math.min(350, NumCast(target._width, 350))} + PanelHeight={() => Math.min(250, NumCast(target._height, 250))} + focus={emptyFunction} + whenActiveChanged={returnFalse} + bringToFront={returnFalse} + ContentScaling={returnOne} + NativeWidth={returnZero} + NativeHeight={returnZero} + /> + </div> + </div>; + FormattedTextBoxComment.showCommentbox("", view, nbef); + + ReactDOM.render(docPreview, FormattedTextBoxComment.tooltipText); + FormattedTextBoxComment.tooltip.style.width = NumCast(target._width) ? `${NumCast(target._width)}` : "100%"; FormattedTextBoxComment.tooltip.style.height = NumCast(target._height) ? `${NumCast(target._height)}` : "100%"; } @@ -248,4 +335,4 @@ export class FormattedTextBoxComment { } destroy() { } -} +}
\ No newline at end of file diff --git a/src/client/views/nodes/formattedText/ProsemirrorExampleTransfer.ts b/src/client/views/nodes/formattedText/ProsemirrorExampleTransfer.ts index 9c91d8007..3f73ec436 100644 --- a/src/client/views/nodes/formattedText/ProsemirrorExampleTransfer.ts +++ b/src/client/views/nodes/formattedText/ProsemirrorExampleTransfer.ts @@ -1,7 +1,6 @@ -import { chainCommands, exitCode, joinDown, joinUp, lift, selectParentNode, setBlockType, splitBlockKeepMarks, toggleMark, wrapIn, newlineInCode } from "prosemirror-commands"; +import { chainCommands, exitCode, joinDown, joinUp, lift, deleteSelection, joinBackward, selectNodeBackward, setBlockType, splitBlockKeepMarks, toggleMark, wrapIn, newlineInCode } from "prosemirror-commands"; import { liftTarget } from "prosemirror-transform"; import { redo, undo } from "prosemirror-history"; -import { undoInputRule } from "prosemirror-inputrules"; import { Schema } from "prosemirror-model"; import { liftListItem, sinkListItem } from "./prosemirrorPatches.js"; import { splitListItem, wrapInList, } from "prosemirror-schema-list"; @@ -17,13 +16,17 @@ const mac = typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : export type KeyMap = { [key: string]: any }; -export let updateBullets = (tx2: Transaction, schema: Schema, mapStyle?: string, from?: number, to?: number) => { +export let updateBullets = (tx2: Transaction, schema: Schema, assignedMapStyle?: string, from?: number, to?: number) => { + let mapStyle = assignedMapStyle; tx2.doc.descendants((node: any, offset: any, index: any) => { if ((from === undefined || to === undefined || (from <= offset + node.nodeSize && to >= offset)) && (node.type === schema.nodes.ordered_list || node.type === schema.nodes.list_item)) { const path = (tx2.doc.resolve(offset) as any).path; let depth = Array.from(path).reduce((p: number, c: any) => p + (c.hasOwnProperty("type") && c.type === schema.nodes.ordered_list ? 1 : 0), 0); - if (node.type === schema.nodes.ordered_list) depth++; - tx2.setNodeMarkup(offset, node.type, { ...node.attrs, mapStyle: mapStyle || node.attrs.mapStyle, bulletStyle: depth, }, node.marks); + if (node.type === schema.nodes.ordered_list) { + if (depth === 0 && !assignedMapStyle) mapStyle = node.attrs.mapStyle; + depth++; + } + tx2.setNodeMarkup(offset, node.type, { ...node.attrs, mapStyle, bulletStyle: depth, }, node.marks); } }); return tx2; @@ -43,7 +46,6 @@ export default function buildKeymap<S extends Schema<any>>(schema: S, props: any //History commands bind("Mod-z", undo); - bind("Backspace", undoInputRule); bind("Shift-Mod-z", redo); !mac && bind("Mod-y", redo); @@ -175,6 +177,25 @@ export default function buildKeymap<S extends Schema<any>>(schema: S, props: any } }); + // backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward); + bind("Backspace", (state: EditorState<S>, dispatch: (tx: Transaction<Schema<any, any>>) => void) => { + if (!deleteSelection(state, (tx: Transaction<Schema<any, any>>) => { + dispatch(updateBullets(tx, schema)); + })) { + if (!joinBackward(state, (tx: Transaction<Schema<any, any>>) => { + dispatch(updateBullets(tx, schema)); + })) { + if (!selectNodeBackward(state, (tx: Transaction<Schema<any, any>>) => { + dispatch(updateBullets(tx, schema)); + })) { + return false; + } + } + } + return true; + }); + + //newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock //command to break line bind("Enter", (state: EditorState<S>, dispatch: (tx: Transaction<Schema<any, any>>) => void) => { if (addTextOnRight(false)) return true; @@ -190,11 +211,19 @@ export default function buildKeymap<S extends Schema<any>>(schema: S, props: any const marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks()); const cr = state.selection.$from.node().textContent.endsWith("\n"); if (cr || !newlineInCode(state, dispatch)) { - if (!splitListItem(schema.nodes.list_item)(state, dispatch)) { + if (!splitListItem(schema.nodes.list_item)(state, (tx2: Transaction) => { + const tx3 = updateBullets(tx2, schema); + marks && tx3.ensureMarks([...marks]); + marks && tx3.setStoredMarks([...marks]); + dispatch(tx3); + })) { + const fromattrs = state.selection.$from.node().attrs; if (!splitBlockKeepMarks(state, (tx3: Transaction) => { - splitMetadata(marks, tx3); - if (!liftListItem(schema.nodes.list_item)(tx3, dispatch as ((tx: Transaction<Schema<any, any>>) => void))) { - dispatch(tx3); + const tonode = tx3.selection.$to.node(); + const tx4 = tx3.setNodeMarkup(tx3.selection.to - 1, tonode.type, fromattrs, tonode.marks); + splitMetadata(marks, tx4); + if (!liftListItem(schema.nodes.list_item)(tx4, dispatch as ((tx: Transaction<Schema<any, any>>) => void))) { + dispatch(tx4); } })) { return false; @@ -257,19 +286,6 @@ export default function buildKeymap<S extends Schema<any>>(schema: S, props: any return false; }); - // bind("^", (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => { - // let newNode = schema.nodes.footnote.create({}); - // if (dispatch && state.selection.from === state.selection.to) { - // let tr = state.tr; - // tr.replaceSelectionWith(newNode); // replace insertion with a footnote. - // dispatch(tr.setSelection(new NodeSelection( // select the footnote node to open its display - // tr.doc.resolve( // get the location of the footnote node by subtracting the nodesize of the footnote from the current insertion point anchor (which will be immediately after the footnote node) - // tr.selection.anchor - tr.selection.$anchor.nodeBefore!.nodeSize)))); - // return true; - // } - // return false; - // }); - return keys; } diff --git a/src/client/views/nodes/formattedText/RichTextMenu.scss b/src/client/views/nodes/formattedText/RichTextMenu.scss index 7a0718c16..fbc468292 100644 --- a/src/client/views/nodes/formattedText/RichTextMenu.scss +++ b/src/client/views/nodes/formattedText/RichTextMenu.scss @@ -77,6 +77,12 @@ color: white; } } + .richTextMenu-divider { + margin: auto; + border-left: solid #ffffff70 0.5px; + height: 20px; + width: 1px; + } } .link-menu { diff --git a/src/client/views/nodes/formattedText/RichTextMenu.tsx b/src/client/views/nodes/formattedText/RichTextMenu.tsx index 839943aac..9075a6486 100644 --- a/src/client/views/nodes/formattedText/RichTextMenu.tsx +++ b/src/client/views/nodes/formattedText/RichTextMenu.tsx @@ -1,8 +1,8 @@ import React = require("react"); import { IconProp, library } from '@fortawesome/fontawesome-svg-core'; -import { faBold, faCaretDown, faChevronLeft, faEyeDropper, faHighlighter, faIndent, faItalic, faLink, faPaintRoller, faPalette, faStrikethrough, faSubscript, faSuperscript, faUnderline } from "@fortawesome/free-solid-svg-icons"; +import { faBold, faCaretDown, faChevronLeft, faEyeDropper, faHighlighter, faOutdent, faIndent, faHandPointLeft, faHandPointRight, faItalic, faLink, faPaintRoller, faPalette, faStrikethrough, faSubscript, faSuperscript, faUnderline } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { action, observable } from "mobx"; +import { action, observable, IReactionDisposer, reaction } from "mobx"; import { observer } from "mobx-react"; import { lift, wrapIn } from "prosemirror-commands"; import { Mark, MarkType, Node as ProsNode, NodeType, ResolvedPos } from "prosemirror-model"; @@ -23,9 +23,10 @@ import { updateBullets } from "./ProsemirrorExampleTransfer"; import "./RichTextMenu.scss"; import { schema } from "./schema_rts"; import { TraceMobx } from "../../../../fields/util"; +import { UndoManager } from "../../../util/UndoManager"; const { toggleMark } = require("prosemirror-commands"); -library.add(faBold, faItalic, faChevronLeft, faUnderline, faStrikethrough, faSuperscript, faSubscript, faIndent, faEyeDropper, faCaretDown, faPalette, faHighlighter, faLink, faPaintRoller); +library.add(faBold, faItalic, faChevronLeft, faUnderline, faStrikethrough, faSuperscript, faSubscript, faOutdent, faIndent, faHandPointLeft, faHandPointRight, faEyeDropper, faCaretDown, faPalette, faHighlighter, faLink, faPaintRoller); @observer @@ -54,6 +55,7 @@ export default class RichTextMenu extends AntimodeMenu { @observable private activeFontSize: string = ""; @observable private activeFontFamily: string = ""; @observable private activeListType: string = ""; + @observable private activeAlignment: string = "left"; @observable private brushIsEmpty: boolean = true; @observable private brushMarks: Set<Mark> = new Set(); @@ -68,6 +70,8 @@ export default class RichTextMenu extends AntimodeMenu { @observable private currentLink: string | undefined = ""; @observable private showLinkDropdown: boolean = false; + _reaction: IReactionDisposer | undefined; + _delayHide = false; constructor(props: Readonly<{}>) { super(props); RichTextMenu.Instance = this; @@ -88,7 +92,7 @@ export default class RichTextMenu extends AntimodeMenu { { mark: schema.marks.pFontSize.create({ fontSize: 32 }), title: "Set font size", label: "32pt", command: this.changeFontSize }, { mark: schema.marks.pFontSize.create({ fontSize: 48 }), title: "Set font size", label: "48pt", command: this.changeFontSize }, { mark: schema.marks.pFontSize.create({ fontSize: 72 }), title: "Set font size", label: "72pt", command: this.changeFontSize }, - { mark: null, title: "", label: "various", command: unimplementedFunction, hidden: true }, + { mark: null, title: "", label: "...", command: unimplementedFunction, hidden: true }, { mark: null, title: "", label: "13pt", command: unimplementedFunction, hidden: true }, // this is here because the default size is 13, but there is no actual 13pt option ]; @@ -107,7 +111,7 @@ export default class RichTextMenu extends AntimodeMenu { this.listTypeOptions = [ { node: schema.nodes.ordered_list.create({ mapStyle: "bullet" }), title: "Set list type", label: ":", command: this.changeListType }, { node: schema.nodes.ordered_list.create({ mapStyle: "decimal" }), title: "Set list type", label: "1.1", command: this.changeListType }, - { node: schema.nodes.ordered_list.create({ mapStyle: "multi" }), title: "Set list type", label: "1.A", command: this.changeListType }, + { node: schema.nodes.ordered_list.create({ mapStyle: "multi" }), title: "Set list type", label: "A.1", command: this.changeListType }, //{ node: undefined, title: "Set list type", label: "Remove", command: this.changeListType }, ]; @@ -138,6 +142,16 @@ export default class RichTextMenu extends AntimodeMenu { ]; } + componentDidMount() { + this._reaction = reaction(() => SelectionManager.SelectedDocuments(), + () => this._delayHide && !(this._delayHide = false) && this.fadeOut(true)); + } + componentWillUnmount() { + this._reaction?.(); + } + + public delayHide = () => this._delayHide = true; + @action changeView(view: EditorView) { this.view = view; @@ -147,16 +161,6 @@ export default class RichTextMenu extends AntimodeMenu { this.updateFromDash(view, lastState, this.editorProps); } - public MakeLinkToSelection = (linkDocId: string, title: string, location: string, targetDocId: string): string => { - if (this.view) { - const link = this.view.state.schema.marks.link.create({ href: Utils.prepend("/doc/" + linkDocId), title: title, location: location, linkId: linkDocId, targetId: targetDocId }); - this.view.dispatch(this.view.state.tr.removeMark(this.view.state.selection.from, this.view.state.selection.to, this.view.state.schema.marks.link). - addMark(this.view.state.selection.from, this.view.state.selection.to, link)); - return this.view.state.selection.$from.nodeAfter?.text || ""; - } - return ""; - } - @action public async updateFromDash(view: EditorView, lastState: EditorState | undefined, props: any) { if (!view) { @@ -175,11 +179,13 @@ export default class RichTextMenu extends AntimodeMenu { // update active font family and size const active = this.getActiveFontStylesOnSelection(); - const activeFamilies = active?.get("families"); - const activeSizes = active?.get("sizes"); + const activeFamilies = active.activeFamilies; + const activeSizes = active.activeSizes; - this.activeFontFamily = !activeFamilies?.length ? "Arial" : activeFamilies.length === 1 ? String(activeFamilies[0]) : "various"; - this.activeFontSize = !activeSizes?.length ? "13pt" : activeSizes.length === 1 ? String(activeSizes[0]) : "various"; + this.activeListType = this.getActiveListStyle(); + this.activeAlignment = this.getActiveAlignment(); + this.activeFontFamily = !activeFamilies.length ? "Arial" : activeFamilies.length === 1 ? String(activeFamilies[0]) : "various"; + this.activeFontSize = !activeSizes.length ? "13pt" : activeSizes.length === 1 ? String(activeSizes[0]) : "..."; // update link in current selection const targetTitle = await this.getTextLinkTargetTitle(); @@ -210,8 +216,34 @@ export default class RichTextMenu extends AntimodeMenu { } // finds font sizes and families in selection + getActiveAlignment() { + if (this.view) { + const path = (this.view.state.selection.$from as any).path; + for (let i = path.length - 3; i < path.length; i -= 3) { + if (path[i]?.type === this.view.state.schema.nodes.paragraph) { + return path[i].attrs.align || "left"; + } + } + } + return "left"; + } + + // finds font sizes and families in selection + getActiveListStyle() { + if (this.view) { + const path = (this.view.state.selection.$from as any).path; + for (let i = 0; i < path.length; i += 3) { + if (path[i].type === this.view.state.schema.nodes.ordered_list) { + return path[i].attrs.mapStyle; + } + } + } + return "decimal"; + } + + // finds font sizes and families in selection getActiveFontStylesOnSelection() { - if (!this.view) return; + if (!this.view) return { activeFamilies: [], activeSizes: [] }; const activeFamilies: string[] = []; const activeSizes: string[] = []; @@ -225,10 +257,7 @@ export default class RichTextMenu extends AntimodeMenu { }); } - const styles = new Map<String, String[]>(); - styles.set("families", activeFamilies); - styles.set("sizes", activeSizes); - return styles; + return { activeFamilies, activeSizes }; } getMarksInSelection(state: EditorState<any>) { @@ -310,8 +339,11 @@ export default class RichTextMenu extends AntimodeMenu { function onClick(e: React.PointerEvent) { e.preventDefault(); e.stopPropagation(); - self.view && command && command(self.view.state, self.view.dispatch, self.view); - self.view && onclick && onclick(self.view.state, self.view.dispatch, self.view); + self.TextView.endUndoTypingBatch(); + UndoManager.RunInBatch(() => { + self.view && command && command(self.view.state, self.view.dispatch, self.view); + self.view && onclick && onclick(self.view.state, self.view.dispatch, self.view); + }, "rich text menu command"); self.setActiveMarkButtons(self.getActiveMarksOnSelection()); } @@ -338,16 +370,18 @@ export default class RichTextMenu extends AntimodeMenu { function onChange(e: React.ChangeEvent<HTMLSelectElement>) { e.stopPropagation(); e.preventDefault(); + self.TextView.endUndoTypingBatch(); options.forEach(({ label, mark, command }) => { if (e.target.value === label) { - self.view && mark && command(mark, self.view); + UndoManager.RunInBatch(() => self.view && mark && command(mark, self.view), "text mark dropdown"); } }); } return <select onChange={onChange} key={key}>{items}</select>; } - createNodesDropdown(activeOption: string, options: { node: NodeType | any | null, title: string, label: string, command: (node: NodeType | any) => void, hidden?: boolean, style?: {} }[], key: string): JSX.Element { + createNodesDropdown(activeMap: string, options: { node: NodeType | any | null, title: string, label: string, command: (node: NodeType | any) => void, hidden?: boolean, style?: {} }[], key: string): JSX.Element { + const activeOption = activeMap === "bullet" ? ":" : activeMap === "decimal" ? "1.1" : "A.1"; const items = options.map(({ title, label, hidden, style }) => { if (hidden) { return label === activeOption ? @@ -361,9 +395,10 @@ export default class RichTextMenu extends AntimodeMenu { const self = this; function onChange(val: string) { + self.TextView.endUndoTypingBatch(); options.forEach(({ label, node, command }) => { if (val === label) { - self.view && node && command(node); + UndoManager.RunInBatch(() => self.view && node && command(node), "nodes dropdown"); } }); } @@ -412,6 +447,85 @@ export default class RichTextMenu extends AntimodeMenu { dispatch?.(tr.replaceSelectionWith(newNode).removeMark(tr.selection.from - 1, tr.selection.from, mark)); return true; } + alignCenter = (state: EditorState<any>, dispatch: any) => { + return this.alignParagraphs(state, "center", dispatch); + } + alignLeft = (state: EditorState<any>, dispatch: any) => { + return this.alignParagraphs(state, "left", dispatch); + } + alignRight = (state: EditorState<any>, dispatch: any) => { + return this.alignParagraphs(state, "right", dispatch); + } + + alignParagraphs(state: EditorState<any>, align: "left" | "right" | "center", dispatch: any) { + var tr = state.tr; + state.doc.nodesBetween(state.selection.from, state.selection.to, (node, pos, parent, index) => { + if (node.type === schema.nodes.paragraph) { + tr = tr.setNodeMarkup(pos, node.type, { ...node.attrs, align }, node.marks); + return false; + } + return true; + }); + dispatch?.(tr); + return true; + } + + insetParagraph(state: EditorState<any>, dispatch: any) { + var tr = state.tr; + state.doc.nodesBetween(state.selection.from, state.selection.to, (node, pos, parent, index) => { + if (node.type === schema.nodes.paragraph) { + const inset = (node.attrs.inset ? Number(node.attrs.inset) : 0) + 10; + tr = tr.setNodeMarkup(pos, node.type, { ...node.attrs, inset }, node.marks); + return false; + } + return true; + }); + dispatch?.(tr); + return true; + } + outsetParagraph(state: EditorState<any>, dispatch: any) { + var tr = state.tr; + state.doc.nodesBetween(state.selection.from, state.selection.to, (node, pos, parent, index) => { + if (node.type === schema.nodes.paragraph) { + const inset = Math.max(0, (node.attrs.inset ? Number(node.attrs.inset) : 0) - 10); + tr = tr.setNodeMarkup(pos, node.type, { ...node.attrs, inset }, node.marks); + return false; + } + return true; + }); + dispatch?.(tr); + return true; + } + + indentParagraph(state: EditorState<any>, dispatch: any) { + var tr = state.tr; + state.doc.nodesBetween(state.selection.from, state.selection.to, (node, pos, parent, index) => { + if (node.type === schema.nodes.paragraph) { + const nodeval = node.attrs.indent ? Number(node.attrs.indent) : undefined; + const indent = !nodeval ? 25 : nodeval < 0 ? 0 : nodeval + 25; + tr = tr.setNodeMarkup(pos, node.type, { ...node.attrs, indent }, node.marks); + return false; + } + return true; + }); + dispatch?.(tr); + return true; + } + + hangingIndentParagraph(state: EditorState<any>, dispatch: any) { + var tr = state.tr; + state.doc.nodesBetween(state.selection.from, state.selection.to, (node, pos, parent, index) => { + if (node.type === schema.nodes.paragraph) { + const nodeval = node.attrs.indent ? Number(node.attrs.indent) : undefined; + const indent = !nodeval ? -25 : nodeval > 0 ? 0 : nodeval - 10; + tr = tr.setNodeMarkup(pos, node.type, { ...node.attrs, indent }, node.marks); + return false; + } + return true; + }); + dispatch?.(tr); + return true; + } insertBlockquote(state: EditorState<any>, dispatch: any) { const path = (state.selection.$from as any).path; @@ -423,6 +537,11 @@ export default class RichTextMenu extends AntimodeMenu { return true; } + insertHorizontalRule(state: EditorState<any>, dispatch: any) { + dispatch(state.tr.replaceSelectionWith(state.schema.nodes.horizontal_rule.create()).scrollIntoView()); + return true; + } + @action toggleBrushDropdown() { this.showBrushDropdown = !this.showBrushDropdown; } // todo: add brushes to brushMap to save with a style name @@ -439,7 +558,8 @@ export default class RichTextMenu extends AntimodeMenu { function onBrushClick(e: React.PointerEvent) { e.preventDefault(); e.stopPropagation(); - self.view && self.fillBrush(self.view.state, self.view.dispatch); + self.TextView.endUndoTypingBatch(); + UndoManager.RunInBatch(() => self.view && self.fillBrush(self.view.state, self.view.dispatch), "rt brush"); } let label = "Stored marks: "; @@ -506,19 +626,24 @@ export default class RichTextMenu extends AntimodeMenu { @action toggleColorDropdown() { this.showColorDropdown = !this.showColorDropdown; } @action setActiveColor(color: string) { this.activeFontColor = color; } + get TextView() { return (this.view as any).TextView as FormattedTextBox; } createColorButton() { const self = this; function onColorClick(e: React.PointerEvent) { e.preventDefault(); e.stopPropagation(); - self.view && self.insertColor(self.activeFontColor, self.view.state, self.view.dispatch); + self.TextView.endUndoTypingBatch(); + UndoManager.RunInBatch(() => self.view && self.insertColor(self.activeFontColor, self.view.state, self.view.dispatch), "rt menu color"); + self.TextView.EditorView!.focus(); } function changeColor(e: React.PointerEvent, color: string) { e.preventDefault(); e.stopPropagation(); self.setActiveColor(color); - self.view && self.insertColor(self.activeFontColor, self.view.state, self.view.dispatch); + self.TextView.endUndoTypingBatch(); + UndoManager.RunInBatch(() => self.view && self.insertColor(self.activeFontColor, self.view.state, self.view.dispatch), "rt menu color"); + self.TextView.EditorView!.focus(); } const button = @@ -563,13 +688,15 @@ export default class RichTextMenu extends AntimodeMenu { function onHighlightClick(e: React.PointerEvent) { e.preventDefault(); e.stopPropagation(); - self.view && self.insertHighlight(self.activeHighlightColor, self.view.state, self.view.dispatch); + self.TextView.endUndoTypingBatch(); + UndoManager.RunInBatch(() => self.view && self.insertHighlight(self.activeHighlightColor, self.view.state, self.view.dispatch), "rt highligher"); } function changeHighlight(e: React.PointerEvent, color: string) { e.preventDefault(); e.stopPropagation(); self.setActiveHighlight(color); - self.view && self.insertHighlight(self.activeHighlightColor, self.view.state, self.view.dispatch); + self.TextView.endUndoTypingBatch(); + UndoManager.RunInBatch(() => self.view && self.insertHighlight(self.activeHighlightColor, self.view.state, self.view.dispatch), "rt highlighter"); } const button = @@ -609,7 +736,8 @@ export default class RichTextMenu extends AntimodeMenu { const self = this; function onLinkChange(e: React.ChangeEvent<HTMLInputElement>) { - self.setCurrentLink(e.target.value); + self.TextView.endUndoTypingBatch(); + UndoManager.RunInBatch(() => self.setCurrentLink(e.target.value), "link change"); } const link = this.currentLink ? this.currentLink : ""; @@ -636,7 +764,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.allHrefs.length > 0 ? link.attrs.allHrefs[0].href : undefined; + const href = link.attrs.allLinks.length > 0 ? link.attrs.allLinks[0].href : undefined; if (href) { if (href.indexOf(Utils.prepend("/doc/")) === 0) { const linkclicked = href.replace(Utils.prepend("/doc/"), "").split("?")[0]; @@ -671,40 +799,28 @@ export default class RichTextMenu extends AntimodeMenu { } deleteLink = () => { - if (!this.view) return; - - 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.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]; - if (linkclicked) { - DocServer.GetRefField(linkclicked).then(async linkDoc => { - if (linkDoc instanceof Doc) { - LinkManager.Instance.deleteLink(linkDoc); - this.view!.dispatch(this.view!.state.tr.removeMark(this.view!.state.selection.from, this.view!.state.selection.to, this.view!.state.schema.marks.link)); - } - }); - } - } else { - if (node) { - const { tr, schema, selection } = this.view.state; - const extension = this.linkExtend(selection.$anchor, href); - this.view.dispatch(tr.removeMark(extension.from, extension.to, schema.marks.link)); - } + if (this.view) { + const link = this.view.state.selection.$from.nodeAfter?.marks.find(m => m.type === this.view!.state.schema.marks.linkAnchor); + if (link) { + const allLinks = link.attrs.allLinks.slice(); + this.TextView.RemoveLinkFromSelection(link.attrs.allLinks); + // bcz: Argh ... this will remove the link from the document even it's anchored somewhere else in the text which happens if only part of the anchor text was selected. + allLinks.filter((aref: any) => aref?.href.indexOf(Utils.prepend("/doc/")) === 0).forEach((aref: any) => { + const linkId = aref.href.replace(Utils.prepend("/doc/"), "").split("?")[0]; + linkId && DocServer.GetRefField(linkId).then(linkDoc => LinkManager.Instance.deleteLink(linkDoc as Doc)); + }); } } } linkExtend($start: ResolvedPos, href: string) { - const mark = this.view!.state.schema.marks.link; + const mark = this.view!.state.schema.marks.linkAnchor; let startIndex = $start.index(); let endIndex = $start.indexAfter(); - 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++; + while (startIndex > 0 && $start.parent.child(startIndex - 1).marks.filter(m => m.type === mark && m.attrs.allLinks.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.allLinks.find((item: { href: string }) => item.href === href)).length) endIndex++; let startPos = $start.start(); let endPos = startPos; @@ -744,7 +860,7 @@ export default class RichTextMenu extends AntimodeMenu { return ref_node; } - @action onPointerEnter(e: React.PointerEvent) { RichTextMenu.Instance.overMenu = true; } + @action onPointerEnter(e: React.PointerEvent) { RichTextMenu.Instance.overMenu = false; } @action onPointerLeave(e: React.PointerEvent) { RichTextMenu.Instance.overMenu = false; } @action @@ -768,26 +884,41 @@ export default class RichTextMenu extends AntimodeMenu { TraceMobx(); const row1 = <div className="antimodeMenu-row" key="row1" style={{ display: this.collapsed ? "none" : undefined }}>{[ !this.collapsed ? this.getDragger() : (null), - this.createButton("bold", "Bold", this.boldActive, toggleMark(schema.marks.strong)), - this.createButton("italic", "Italic", this.italicsActive, toggleMark(schema.marks.em)), - this.createButton("underline", "Underline", this.underlineActive, toggleMark(schema.marks.underline)), - this.createButton("strikethrough", "Strikethrough", this.strikethroughActive, toggleMark(schema.marks.strikethrough)), - this.createButton("superscript", "Superscript", this.superscriptActive, toggleMark(schema.marks.superscript)), - this.createButton("subscript", "Subscript", this.subscriptActive, toggleMark(schema.marks.subscript)), + !this.Pinned ? (null) : <> {[ + this.createButton("bold", "Bold", this.boldActive, toggleMark(schema.marks.strong)), + this.createButton("italic", "Italic", this.italicsActive, toggleMark(schema.marks.em)), + this.createButton("underline", "Underline", this.underlineActive, toggleMark(schema.marks.underline)), + this.createButton("strikethrough", "Strikethrough", this.strikethroughActive, toggleMark(schema.marks.strikethrough)), + this.createButton("superscript", "Superscript", this.superscriptActive, toggleMark(schema.marks.superscript)), + this.createButton("subscript", "Subscript", this.subscriptActive, toggleMark(schema.marks.subscript)), + <div className="richTextMenu-divider" /> + ]}</>, this.createColorButton(), this.createHighlighterButton(), this.createLinkButton(), this.createBrushButton(), - this.createButton("sort-amount-down", "Summarize", undefined, this.insertSummarizer), - this.createButton("quote-left", "Blockquote", undefined, this.insertBlockquote), + <div className="richTextMenu-divider" />, + this.createButton("align-left", "Align Left", this.activeAlignment === "left", this.alignLeft), + this.createButton("align-center", "Align Center", this.activeAlignment === "center", this.alignCenter), + this.createButton("align-right", "Align Right", this.activeAlignment === "right", this.alignRight), + this.createButton("indent", "Inset More", undefined, this.insetParagraph), + this.createButton("outdent", "Inset Less", undefined, this.outsetParagraph), + this.createButton("hand-point-left", "Hanging Indent", undefined, this.hangingIndentParagraph), + this.createButton("hand-point-right", "Indent", undefined, this.indentParagraph), ]}</div>; const row2 = <div className="antimodeMenu-row row-2" key="antimodemenu row2"> {this.collapsed ? this.getDragger() : (null)} <div key="row" style={{ display: this.collapsed ? "none" : undefined }}> + <div className="richTextMenu-divider" />, {[this.createMarksDropdown(this.activeFontSize, this.fontSizeOptions, "font size"), this.createMarksDropdown(this.activeFontFamily, this.fontFamilyOptions, "font family"), - this.createNodesDropdown(this.activeListType, this.listTypeOptions, "nodes")]} + <div className="richTextMenu-divider" />, + this.createNodesDropdown(this.activeListType, this.listTypeOptions, "nodes"), + this.createButton("sort-amount-down", "Summarize", undefined, this.insertSummarizer), + this.createButton("quote-left", "Blockquote", undefined, this.insertBlockquote), + this.createButton("minus", "Horizontal Rule", undefined, this.insertHorizontalRule), + <div className="richTextMenu-divider" />,]} </div> <div key="button"> {/* <div key="collapser"> @@ -817,7 +948,7 @@ interface ButtonDropdownProps { } @observer -class ButtonDropdown extends React.Component<ButtonDropdownProps> { +export class ButtonDropdown extends React.Component<ButtonDropdownProps> { @observable private showDropdown: boolean = false; private ref: HTMLDivElement | null = null; diff --git a/src/client/views/nodes/formattedText/RichTextRules.ts b/src/client/views/nodes/formattedText/RichTextRules.ts index ba3230801..ca30dde9d 100644 --- a/src/client/views/nodes/formattedText/RichTextRules.ts +++ b/src/client/views/nodes/formattedText/RichTextRules.ts @@ -275,11 +275,11 @@ export class RichTextRules { if (!fieldKey) { if (docid) { DocServer.GetRefField(docid).then(docx => { - const target = ((docx instanceof Doc) && docx) || Docs.Create.FreeformDocument([], { title: docid, _width: 500, _height: 500, _LODdisable: true, }, docid); + const target = ((docx instanceof Doc) && docx) || Docs.Create.FreeformDocument([], { title: docid, _width: 500, _height: 500, }, docid); DocUtils.Publish(target, docid, returnFalse, returnFalse); DocUtils.MakeLink({ doc: this.Document }, { doc: target }, "portal to"); }); - const link = state.schema.marks.link.create({ href: Utils.prepend("/doc/" + docid), location: "onRight", title: docid, targetId: docid }); + const link = state.schema.marks.linkAnchor.create({ href: Utils.prepend("/doc/" + docid), location: "onRight", title: docid, targetId: docid }); return state.tr.deleteRange(end - 1, end).deleteRange(start, start + 2).addMark(start, end - 3, link); } return state.tr; @@ -305,7 +305,7 @@ export class RichTextRules { if (!fieldKey && !docid) return state.tr; docid && DocServer.GetRefField(docid).then(docx => { if (!(docx instanceof Doc && docx)) { - const docx = Docs.Create.FreeformDocument([], { title: docid, _width: 500, _height: 500, _LODdisable: true }, docid); + const docx = Docs.Create.FreeformDocument([], { title: docid, _width: 500, _height: 500 }, docid); DocUtils.Publish(docx, docid, returnFalse, returnFalse); } }); @@ -315,8 +315,6 @@ export class RichTextRules { return node ? state.tr.replaceRangeWith(start, end, dashDoc).setStoredMarks([...node.marks, ...(sm ? sm : [])]) : state.tr; }), - - // create an inline view of a tag stored under the '#' field new InputRule( new RegExp(/#([a-zA-Z_\-]+[a-zA-Z_;\-0-9]*)\s$/), @@ -374,7 +372,6 @@ export class RichTextRules { new InputRule( new RegExp(/%\)/), (state, match, start, end) => { - return state.tr.deleteRange(start, end).removeStoredMark(state.schema.marks.summarizeInclusive.create()); }), diff --git a/src/client/views/nodes/formattedText/marks_rts.ts b/src/client/views/nodes/formattedText/marks_rts.ts index 1de211f28..3d7d71b14 100644 --- a/src/client/views/nodes/formattedText/marks_rts.ts +++ b/src/client/views/nodes/formattedText/marks_rts.ts @@ -17,12 +17,12 @@ export const marks: { [index: string]: MarkSpec } = { return ["div", { className: "dummy" }, 0]; } }, - // :: MarkSpec A link. Has `href` and `title` attributes. `title` + // :: MarkSpec A linkAnchor. The anchor can have multiple links, where each link has an href URL and a title for use in menus and hover (Dash links have linkIDs & targetIDs). `title` // defaults to the empty string. Rendered and parsed as an `<a>` // element. - link: { + linkAnchor: { attrs: { - allHrefs: { default: [] as { href: string, title: string, linkId: string, targetId: string }[] }, + allLinks: { default: [] as { href: string, title: string, linkId: string, targetId: string }[] }, showPreview: { default: true }, location: { default: null }, title: { default: null }, @@ -31,22 +31,22 @@ export const marks: { [index: string]: MarkSpec } = { inclusive: false, parseDOM: [{ tag: "a[href]", getAttrs(dom: any) { - return { allHrefs: [{ href: dom.getAttribute("href"), title: dom.getAttribute("title"), linkId: dom.getAttribute("linkids"), targetId: dom.getAttribute("targetids") }], location: dom.getAttribute("location"), }; + return { allLinks: [{ 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, ""); + const targetids = node.attrs.allLinks.reduce((p: string, item: { href: string, title: string, targetId: string, linkId: string }) => p + " " + item.targetId, ""); + const linkids = node.attrs.allLinks.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"]] : - node.attrs.allHrefs.length === 1 ? - ["a", { ...node.attrs, class: linkids, targetids, title: `${node.attrs.title}`, href: node.attrs.allHrefs[0].href }, 0] : + ["div", ["span", `"`], ["span", 0], ["span", `"`], ["br"], ["a", { ...node.attrs, href: node.attrs.allLinks[0].href, class: "prosemirror-attribution" }, node.attrs.title], ["br"]] : + node.attrs.allLinks.length === 1 ? + ["a", { ...node.attrs, class: linkids, targetids, title: `${node.attrs.title}`, href: node.attrs.allLinks[0].href }, 0] : ["div", { class: "prosemirror-anchor" }, ["span", { 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 }) => + ["div", { class: "prosemirror-links" }, ...node.attrs.allLinks.map((item: { href: string, title: string }) => ["a", { class: "prosemirror-dropdownlink", href: item.href }, item.title] )] ]; @@ -270,6 +270,7 @@ export const marks: { [index: string]: MarkSpec } = { userid: { default: "" }, modified: { default: "when?" }, // 1 second intervals since 1970 }, + excludes: "user_mark", group: "inline", toDOM(node: any) { const uid = node.attrs.userid.replace(".", "").replace("@", ""); diff --git a/src/client/views/nodes/formattedText/nodes_rts.ts b/src/client/views/nodes/formattedText/nodes_rts.ts index 0a867912f..1af821738 100644 --- a/src/client/views/nodes/formattedText/nodes_rts.ts +++ b/src/client/views/nodes/formattedText/nodes_rts.ts @@ -302,7 +302,7 @@ export const nodes: { [index: string]: NodeSpec } = { mapStyle: { default: "decimal" }, // "decimal", "multi", "bullet" visibility: { default: true } }, - content: 'paragraph block*', + content: 'paragraph+ | (paragraph ordered_list)', parseDOM: [{ tag: "li", getAttrs(dom: any) { return { mapStyle: dom.getAttribute("data-mapStyle"), bulletStyle: dom.getAttribute("data-bulletStyle") }; @@ -310,9 +310,9 @@ export const nodes: { [index: string]: NodeSpec } = { }], toDOM(node: any) { const map = node.attrs.bulletStyle ? node.attrs.mapStyle + node.attrs.bulletStyle : ""; - return node.attrs.visibility ? - ["li", { class: `${map}`, "data-mapStyle": node.attrs.mapStyle, "data-bulletStyle": node.attrs.bulletStyle }, 0] : - ["li", { class: `${map}`, "data-mapStyle": node.attrs.mapStyle, "data-bulletStyle": node.attrs.bulletStyle }, "..."]; + return ["li", { class: `${map}`, "data-mapStyle": node.attrs.mapStyle, "data-bulletStyle": node.attrs.bulletStyle }, node.attrs.visibility ? 0 : + ["span", { style: `position: relative; width: 100%; height: 1.5em; overflow: hidden; display: ${node.attrs.mapStyle !== "bullet" ? "inline-block" : "list-item"}; text-overflow: ellipsis; white-space: pre` }, + `${node.firstChild?.textContent}...`]]; } }, };
\ No newline at end of file diff --git a/src/client/views/nodes/formattedText/prosemirrorPatches.js b/src/client/views/nodes/formattedText/prosemirrorPatches.js index 763961958..0969ea4ef 100644 --- a/src/client/views/nodes/formattedText/prosemirrorPatches.js +++ b/src/client/views/nodes/formattedText/prosemirrorPatches.js @@ -9,6 +9,7 @@ var prosemirrorModel = require('prosemirror-model'); exports.liftListItem = liftListItem; exports.sinkListItem = sinkListItem; exports.wrappingInputRule = wrappingInputRule; +exports.removeMarkWithAttrs = removeMarkWithAttrs; // :: (NodeType) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool // Create a command to lift the list item around the selection up into // a wrapping list. @@ -139,3 +140,57 @@ function wrappingInputRule(regexp, nodeType, getAttrs, joinPredicate, customWith } +// :: ([Mark]) → ?Mark +// Tests whether there is a mark of this type in the given set. +function isInSetWithAttrs(mark, set, attrs) { + for (var i = 0; i < set.length; i++) { + if (set[i].type == mark) { + if (Array.from(Object.keys(attrs)).reduce((p, akey) => { + return p && JSON.stringify(set[i].attrs[akey]) === JSON.stringify(attrs[akey]); + }, true)) { + return set[i]; + } + } + } +}; + +// :: (number, number, ?union<Mark, MarkType>) → this +// Remove marks from inline nodes between `from` and `to`. When `mark` +// is a single mark, remove precisely that mark. When it is a mark type, +// remove all marks of that type. When it is null, remove all marks of +// any type. +function removeMarkWithAttrs(tr, from, to, mark, attrs) { + if (mark === void 0) mark = null; + + var matched = [], step = 0; + tr.doc.nodesBetween(from, to, function (node, pos) { + if (!node.isInline) { return } + step++; + var toRemove = null; + if (mark) { + if (isInSetWithAttrs(mark, node.marks, attrs)) { toRemove = [mark]; } + } else { + toRemove = node.marks; + } + if (toRemove && toRemove.length) { + var end = Math.min(pos + node.nodeSize, to); + for (var i = 0; i < toRemove.length; i++) { + var style = toRemove[i], found$1 = (void 0); + for (var j = 0; j < matched.length; j++) { + var m = matched[j]; + if (m.step == step - 1 && style.eq(matched[j].style)) { found$1 = m; } + } + if (found$1) { + found$1.to = end; + found$1.step = step; + } else { + matched.push({ style: style, from: Math.max(pos, from), to: end, step: step }); + } + } + } + }); + matched.forEach(function (m) { return tr.step(new prosemirrorTransform.RemoveMarkStep(m.from, m.to, m.style)); }); + return tr +}; + + diff --git a/src/client/views/pdf/Annotation.tsx b/src/client/views/pdf/Annotation.tsx index cb6a15f36..d29b638e6 100644 --- a/src/client/views/pdf/Annotation.tsx +++ b/src/client/views/pdf/Annotation.tsx @@ -8,7 +8,6 @@ import { Cast, FieldValue, NumCast, StrCast } from "../../../fields/Types"; import { DocumentManager } from "../../util/DocumentManager"; import PDFMenu from "./PDFMenu"; import "./Annotation.scss"; -import { DocumentView } from "../nodes/DocumentView"; interface IAnnotationProps { anno: Doc; @@ -19,7 +18,9 @@ interface IAnnotationProps { fieldKey: string; } -export default class Annotation extends React.Component<IAnnotationProps> { +@observer +export default + class Annotation extends React.Component<IAnnotationProps> { render() { return DocListCast(this.props.anno.annotations).map(a => ( <RegionAnnotation {...this.props} document={a} x={NumCast(a.x)} y={NumCast(a.y)} width={a[WidthSym]()} height={a[HeightSym]()} key={a[Id]} />)); diff --git a/src/client/views/pdf/PDFMenu.scss b/src/client/views/pdf/PDFMenu.scss index 3c08ba80d..fa43a99b2 100644 --- a/src/client/views/pdf/PDFMenu.scss +++ b/src/client/views/pdf/PDFMenu.scss @@ -3,4 +3,23 @@ width: 200px; padding: 5px; grid-template-columns: 90px 20px 90px; +} + +.color-wrapper { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + + button.color-button { + width: 20px; + height: 20px; + border-radius: 15px !important; + margin: 3px; + border: 2px solid transparent !important; + padding: 3px; + + &.active { + border: 2px solid white; + } + } }
\ No newline at end of file diff --git a/src/client/views/pdf/PDFMenu.tsx b/src/client/views/pdf/PDFMenu.tsx index a641bce67..00c56d73e 100644 --- a/src/client/views/pdf/PDFMenu.tsx +++ b/src/client/views/pdf/PDFMenu.tsx @@ -1,22 +1,43 @@ import React = require("react"); import "./PDFMenu.scss"; -import { observable, action, } from "mobx"; +import { observable, action, computed, } from "mobx"; import { observer } from "mobx-react"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { unimplementedFunction, returnFalse } from "../../../Utils"; +import { unimplementedFunction, returnFalse, Utils } from "../../../Utils"; import AntimodeMenu from "../AntimodeMenu"; import { Doc, Opt } from "../../../fields/Doc"; +import { ColorState } from "react-color"; +import { ButtonDropdown } from "../nodes/formattedText/RichTextMenu"; + @observer export default class PDFMenu extends AntimodeMenu { static Instance: PDFMenu; private _commentCont = React.createRef<HTMLButtonElement>(); + private _palette = [ + "rgba(208, 2, 27, 0.8)", + "rgba(238, 0, 0, 0.8)", + "rgba(245, 166, 35, 0.8)", + "rgba(248, 231, 28, 0.8)", + "rgba(245, 230, 95, 0.616)", + "rgba(139, 87, 42, 0.8)", + "rgba(126, 211, 33, 0.8)", + "rgba(65, 117, 5, 0.8)", + "rgba(144, 19, 254, 0.8)", + "rgba(238, 169, 184, 0.8)", + "rgba(224, 187, 228, 0.8)", + "rgba(225, 223, 211, 0.8)", + "rgba(255, 255, 255, 0.8)", + "rgba(155, 155, 155, 0.8)", + "rgba(0, 0, 0, 0.8)"]; @observable private _keyValue: string = ""; @observable private _valueValue: string = ""; @observable private _added: boolean = false; + @observable private highlightColor: string = "rgba(245, 230, 95, 0.616)"; + @observable public _colorBtn = false; @observable public Highlighting: boolean = false; @observable public Status: "pdf" | "annotation" | "" = ""; @@ -26,6 +47,7 @@ export default class PDFMenu extends AntimodeMenu { public AddTag: (key: string, value: string) => boolean = returnFalse; public PinToPres: () => void = unimplementedFunction; public Marquee: { left: number; top: number; width: number; height: number; } | undefined; + public get Active() { return this._opacity ? true : false; } constructor(props: Readonly<{}>) { super(props); @@ -69,11 +91,47 @@ export default class PDFMenu extends AntimodeMenu { @action highlightClicked = (e: React.MouseEvent) => { - if (!this.Highlight("rgba(245, 230, 95, 0.616)") && this.Pinned) { // yellowish highlight color for a marker type highlight + if (!this.Highlight(this.highlightColor) && this.Pinned) { this.Highlighting = !this.Highlighting; } } + @computed get highlighter() { + const button = + <button className="antimodeMenu-button color-preview-button" title="" key="highilghter-button" onPointerDown={this.highlightClicked}> + <FontAwesomeIcon icon="highlighter" size="lg" style={{ transition: "transform 0.1s", transform: this.Highlighting ? "" : "rotate(-45deg)" }} /> + <div className="color-preview" style={{ backgroundColor: this.highlightColor }}></div> + </button>; + + const dropdownContent = + <div className="dropdown"> + <p>Change highlighter color:</p> + <div className="color-wrapper"> + {this._palette.map(color => { + if (color) { + return this.highlightColor === color ? + <button className="color-button active" key={`active ${color}`} style={{ backgroundColor: color }} onPointerDown={e => this.changeHighlightColor(color, e)}></button> : + <button className="color-button" key={`inactive ${color}`} style={{ backgroundColor: color }} onPointerDown={e => this.changeHighlightColor(color, e)}></button>; + } + })} + </div> + </div>; + return ( + <ButtonDropdown key={"highlighter"} button={button} dropdownContent={dropdownContent} /> + ); + } + + @action + changeHighlightColor = (color: string, e: React.PointerEvent) => { + const col: ColorState = { + hex: color, hsl: { a: 0, h: 0, s: 0, l: 0, source: "" }, hsv: { a: 0, h: 0, s: 0, v: 0, source: "" }, + rgb: { a: 0, r: 0, b: 0, g: 0, source: "" }, oldHue: 0, source: "", + }; + e.preventDefault(); + e.stopPropagation(); + this.highlightColor = Utils.colorString(col); + } + deleteClicked = (e: React.PointerEvent) => { this.Delete(); } @@ -100,12 +158,11 @@ export default class PDFMenu extends AntimodeMenu { render() { const buttons = this.Status === "pdf" ? [ - <button key="1" className="antimodeMenu-button" title="Click to Highlight" onClick={this.highlightClicked} style={this.Highlighting ? { backgroundColor: "#121212" } : {}}> - <FontAwesomeIcon icon="highlighter" size="lg" style={{ transition: "transform 0.1s", transform: this.Highlighting ? "" : "rotate(-45deg)" }} /></button>, + this.highlighter, <button key="2" className="antimodeMenu-button" title="Drag to Annotate" ref={this._commentCont} onPointerDown={this.pointerDown}> <FontAwesomeIcon icon="comment-alt" size="lg" /></button>, <button key="4" className="antimodeMenu-button" title="Pin Menu" onClick={this.togglePin} style={this.Pinned ? { backgroundColor: "#121212" } : {}}> - <FontAwesomeIcon icon="thumbtack" size="lg" style={{ transition: "transform 0.1s", transform: this.Pinned ? "rotate(45deg)" : "" }} /> </button> + <FontAwesomeIcon icon="thumbtack" size="lg" style={{ transition: "transform 0.1s", transform: this.Pinned ? "rotate(45deg)" : "" }} /></button>, ] : [ <button key="5" className="antimodeMenu-button" title="Delete Anchor" onPointerDown={this.deleteClicked}> <FontAwesomeIcon icon="trash-alt" size="lg" /></button>, diff --git a/src/client/views/pdf/PDFViewer.scss b/src/client/views/pdf/PDFViewer.scss index affffc44e..86c73bfee 100644 --- a/src/client/views/pdf/PDFViewer.scss +++ b/src/client/views/pdf/PDFViewer.scss @@ -1,5 +1,5 @@ -.pdfViewer, .pdfViewer-interactive { +.pdfViewerDash, .pdfViewerDash-interactive { width: 100%; height: 100%; position: absolute; @@ -12,14 +12,14 @@ // transform-origin: top left; // } .textLayer { - + opacity: unset; mix-blend-mode: multiply;// bcz: makes text fuzzy! span { padding-right: 5px; padding-bottom: 4px; } } - .textLayer ::selection { background: yellow; } // should match the backgroundColor in createAnnotation() + .textLayer ::selection { background: #ACCEF7; } // should match the backgroundColor in createAnnotation() .textLayer .highlight { background-color: yellow; } @@ -31,26 +31,26 @@ position: relative; border: unset; } - .pdfViewer-text-selected { + .pdfViewerDash-text-selected { .textLayer{ pointer-events: all; user-select: text; } } - .pdfViewer-text { + .pdfViewerDash-text { transform-origin: top left; .textLayer { will-change: transform; } } - .pdfViewer-dragAnnotationBox { + .pdfViewerDash-dragAnnotationBox { position:absolute; background-color: transparent; opacity: 0.1; } - .pdfViewer-overlay, .pdfViewer-overlay-inking { + .pdfViewerDash-overlay, .pdfViewerDash-overlay-inking { transform-origin: left top; position: absolute; top: 0px; @@ -58,11 +58,11 @@ display: inline-block; width:100%; } - .pdfViewer-overlay { + .pdfViewerDash-overlay { pointer-events: none; } - .pdfViewer-annotationLayer { + .pdfViewerDash-annotationLayer { position: absolute; transform-origin: left top; top: 0; @@ -70,12 +70,12 @@ pointer-events: none; mix-blend-mode: multiply; // bcz: makes text fuzzy! - .pdfViewer-annotationBox { + .pdfViewerDash-annotationBox { position: absolute; background-color: rgba(245, 230, 95, 0.616); } } - .pdfViewer-waiting { + .pdfViewerDash-waiting { width: 70%; height: 70%; margin : 15%; @@ -86,7 +86,7 @@ } } -.pdfViewer-interactive { +.pdfViewerDash-interactive { pointer-events: all; }
\ No newline at end of file diff --git a/src/client/views/pdf/PDFViewer.tsx b/src/client/views/pdf/PDFViewer.tsx index 50ffd57fe..4e5fdbfbb 100644 --- a/src/client/views/pdf/PDFViewer.tsx +++ b/src/client/views/pdf/PDFViewer.tsx @@ -1,5 +1,6 @@ import { action, computed, IReactionDisposer, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; +const pdfjs = require('pdfjs-dist/es5/build/pdf.js'); import * as Pdfjs from "pdfjs-dist"; import "pdfjs-dist/web/pdf_viewer.css"; import { Dictionary } from "typescript-collections"; @@ -41,7 +42,10 @@ export const pageSchema = createSchema({ serachMatch: "boolean" }); -pdfjsLib.GlobalWorkerOptions.workerSrc = `/assets/pdf.worker.js`; +//pdfjsLib.GlobalWorkerOptions.workerSrc = `/assets/pdf.worker.js`; +// The workerSrc property shall be specified. +pdfjsLib.GlobalWorkerOptions.workerSrc = "https://unpkg.com/pdfjs-dist@2.4.456/build/pdf.worker.min.js"; + type PdfDocument = makeInterface<[typeof documentSchema, typeof pageSchema]>; const PdfDocument = makeInterface(documentSchema, pageSchema); @@ -80,7 +84,6 @@ interface IViewerProps { export class PDFViewer extends ViewBoxAnnotatableComponent<IViewerProps, PdfDocument>(PdfDocument) { static _annotationStyle: any = addStyleSheet(); @observable private _pageSizes: { width: number, height: number }[] = []; - @observable private _annotations: Doc[] = []; @observable private _savedAnnotations: Dictionary<number, HTMLDivElement[]> = new Dictionary<number, HTMLDivElement[]>(); @observable private _script: CompiledScript = CompileScript("return true") as CompiledScript; @observable private Index: number = -1; @@ -94,7 +97,7 @@ export class PDFViewer extends ViewBoxAnnotatableComponent<IViewerProps, PdfDocu @observable private _zoomed = 1; private _pdfViewer: any; - private _retries = 0; // number of times tried to create the PDF viewer + private _retries = 0; // number of times tried to create the PDF viewer private _setPreviewCursor: undefined | ((x: number, y: number, drag: boolean) => void); private _annotationLayer: React.RefObject<HTMLDivElement> = React.createRef(); private _reactionDisposer?: IReactionDisposer; @@ -111,18 +114,15 @@ export class PDFViewer extends ViewBoxAnnotatableComponent<IViewerProps, PdfDocu private _downX: number = 0; private _downY: number = 0; private _coverPath: any; + private _lastSearch = false; private _viewerIsSetup = false; @computed get allAnnotations() { - return DocListCast(this.dataDoc[this.props.fieldKey + "-annotations"]).filter( - anno => this._script.run({ this: anno }, console.log, true).result); - } - - @computed get nonDocAnnotations() { - return this._annotations.filter(anno => this._script.run({ this: anno }, console.log, true).result); + return DocListCast(this.dataDoc[this.props.fieldKey + "-annotations"]). + filter(anno => this._script.run({ this: anno }, console.log, true).result); } + @computed get nonDocAnnotations() { return this.allAnnotations.filter(a => a.annotations); } - _lastSearch: string = ""; componentDidMount = async () => { // change the address to be the file address of the PNG version of each page // file address of the pdf @@ -148,17 +148,12 @@ export class PDFViewer extends ViewBoxAnnotatableComponent<IViewerProps, PdfDocu } runInAction(() => this._showWaiting = this._showCover = true); this.props.startupLive && this.setupPdfJsViewer(); - this._mainCont.current!.scrollTop = this.layoutDoc._scrollTop || 0; - this._searchReactionDisposer = reaction(() => this.Document.searchMatch, search => { - if (search) { - this.search(Doc.SearchQuery(), true); - this._lastSearch = Doc.SearchQuery(); - } - else { - setTimeout(() => this._lastSearch === "mxytzlaf" && this.search("mxytzlaf", true), 200); // bcz: how do we clear search highlights? - this._lastSearch && (this._lastSearch = "mxytzlaf"); - } - }, { fireImmediately: true }); + this._mainCont.current && (this._mainCont.current.scrollTop = this.layoutDoc._scrollTop || 0); + this._searchReactionDisposer = reaction(() => this.Document.searchMatch, + m => { + if (m) (this._lastSearch = true) && this.search(Doc.SearchQuery(), true); + else !(this._lastSearch = false) && setTimeout(() => !this._lastSearch && this.search("", false, true), 200); + }, { fireImmediately: true }); this._selectionReactionDisposer = reaction(() => this.props.isSelected(), selected => { @@ -231,25 +226,19 @@ export class PDFViewer extends ViewBoxAnnotatableComponent<IViewerProps, PdfDocu await this.initialLoad(); this._scrollTopReactionDisposer = reaction(() => Cast(this.layoutDoc._scrollTop, "number", null), - (stop) => (stop !== undefined && this.layoutDoc._scrollY === undefined) && (this._mainCont.current!.scrollTop = stop), { fireImmediately: true }); - - this._annotationReactionDisposer = reaction( - () => DocListCast(this.dataDoc[this.props.fieldKey + "-annotations"]), - annotations => annotations?.length && (this._annotations = annotations), + (stop) => (stop !== undefined && this.layoutDoc._scrollY === undefined && this._mainCont.current) && (this._mainCont.current.scrollTop = stop), { fireImmediately: true }); this._filterReactionDisposer = reaction( - () => ({ scriptField: Cast(this.Document.filterScript, ScriptField), annos: this._annotations.slice() }), - action(({ scriptField, annos }: { scriptField: FieldResult<ScriptField>, annos: Doc[] }) => { + () => Cast(this.Document.filterScript, ScriptField), + action(scriptField => { const oldScript = this._script.originalScript; - this._script = scriptField && scriptField.script.compiled ? scriptField.script : CompileScript("return true") as CompiledScript; + this._script = scriptField?.script.compiled ? scriptField.script : CompileScript("return true") as CompiledScript; if (this._script.originalScript !== oldScript) { this.Index = -1; } - annos.forEach(d => d.opacity = this._script.run({ this: d }, console.log, 1).result ? 1 : 0); }), - { fireImmediately: true } - ); + { fireImmediately: true }); this.createPdfViewer(); } @@ -270,16 +259,18 @@ export class PDFViewer extends ViewBoxAnnotatableComponent<IViewerProps, PdfDocu } document.removeEventListener("copy", this.copy); document.addEventListener("copy", this.copy); - document.addEventListener("pagesinit", this.pagesinit); - document.addEventListener("pagerendered", action(() => this._showCover = this._showWaiting = false)); + const eventBus = new PDFJSViewer.EventBus(true); + eventBus._on("pagesinit", this.pagesinit); + eventBus._on("pagerendered", action(() => this._showCover = this._showWaiting = false)); const pdfLinkService = new PDFJSViewer.PDFLinkService(); - const pdfFindController = new PDFJSViewer.PDFFindController({ linkService: pdfLinkService }); + const pdfFindController = new PDFJSViewer.PDFFindController({ linkService: pdfLinkService, eventBus }); this._pdfViewer = new PDFJSViewer.PDFViewer({ container: this._mainCont.current, viewer: this._viewer.current, linkService: pdfLinkService, findController: pdfFindController, renderer: "canvas", + eventBus }); pdfLinkService.setViewer(this._pdfViewer); pdfLinkService.setDocument(this.props.pdf, null); @@ -297,7 +288,7 @@ export class PDFViewer extends ViewBoxAnnotatableComponent<IViewerProps, PdfDocu let minY = Number.MAX_VALUE; if ((this._savedAnnotations.values()[0][0] as any).marqueeing) { const anno = this._savedAnnotations.values()[0][0]; - const annoDoc = Docs.Create.FreeformDocument([], { backgroundColor: color, _LODdisable: true, title: "Annotation on " + this.Document.title }); + const annoDoc = Docs.Create.FreeformDocument([], { backgroundColor: color, title: "Annotation on " + this.Document.title }); if (anno.style.left) annoDoc.x = parseInt(anno.style.left); if (anno.style.top) annoDoc.y = parseInt(anno.style.top); if (anno.style.height) annoDoc._height = parseInt(anno.style.height); @@ -385,7 +376,7 @@ export class PDFViewer extends ViewBoxAnnotatableComponent<IViewerProps, PdfDocu div.style.top = (parseInt(div.style.top)/*+ this.getScrollFromPage(page)*/).toString(); } this._annotationLayer.current.append(div); - div.style.backgroundColor = "yellow"; + div.style.backgroundColor = "#ACCEF7"; div.style.opacity = "0.5"; const savedPage = this._savedAnnotations.getValue(page); if (savedPage) { @@ -399,11 +390,12 @@ export class PDFViewer extends ViewBoxAnnotatableComponent<IViewerProps, PdfDocu } @action - search = (searchString: string, fwd: boolean) => { - if (!searchString) { + search = (searchString: string, fwd: boolean, clear: boolean = false) => { + if (clear) { + this._pdfViewer.findController.executeCommand('reset', {}); + } else if (!searchString) { fwd ? this.nextAnnotation() : this.prevAnnotation(); - } - else if (this._pdfViewer._pageViewsReady) { + } else if (this._pdfViewer.pageViewsReady) { this._pdfViewer.findController.executeCommand('findagain', { caseSensitive: false, findPrevious: !fwd, @@ -437,7 +429,7 @@ export class PDFViewer extends ViewBoxAnnotatableComponent<IViewerProps, PdfDocu this._downX = e.clientX; this._downY = e.clientY; addStyleSheetRule(PDFViewer._annotationStyle, "pdfAnnotation", { "pointer-events": "none" }); - if ((this.Document.scale || 1) !== 1) return; + if ((this.Document._viewScale || 1) !== 1) return; if ((e.button !== 0 || e.altKey) && this.active(true)) { this._setPreviewCursor?.(e.clientX, e.clientY, true); //e.stopPropagation(); @@ -501,9 +493,9 @@ export class PDFViewer extends ViewBoxAnnotatableComponent<IViewerProps, PdfDocu if (rect.width !== this._mainCont.current.clientWidth && (i === 0 || !intersectRect(clientRects[i], clientRects[i - 1]))) { const annoBox = document.createElement("div"); - annoBox.className = "pdfViewer-annotationBox"; + annoBox.className = "pdfViewerDash-annotationBox"; // transforms the positions from screen onto the pdf div - annoBox.style.top = ((rect.top - boundingRect.top) * scaleY / this._zoomed + this._mainCont.current.scrollTop).toString(); + annoBox.style.top = ((rect.top - boundingRect.top) * scaleX / this._zoomed + this._mainCont.current.scrollTop).toString(); annoBox.style.left = ((rect.left - boundingRect.left) * scaleX / this._zoomed).toString(); annoBox.style.width = (rect.width * this._mainCont.current.offsetWidth / boundingRect.width / this._zoomed).toString(); annoBox.style.height = (rect.height * this._mainCont.current.offsetHeight / boundingRect.height / this._zoomed).toString(); @@ -528,8 +520,8 @@ export class PDFViewer extends ViewBoxAnnotatableComponent<IViewerProps, PdfDocu this._savedAnnotations.clear(); if (this._marqueeing) { if (this._marqueeWidth > 10 || this._marqueeHeight > 10) { - const marquees = this._mainCont.current!.getElementsByClassName("pdfViewer-dragAnnotationBox"); - if (marquees && marquees.length) { // copy the marquee and convert it to a permanent annotation. + const marquees = this._mainCont.current!.getElementsByClassName("pdfViewerDash-dragAnnotationBox"); + if (marquees && marquees.length) { // copy the marquee and convert it to a permanent annotation. const style = (marquees[0] as HTMLDivElement).style; const copy = document.createElement("div"); copy.style.left = style.left; @@ -539,7 +531,7 @@ export class PDFViewer extends ViewBoxAnnotatableComponent<IViewerProps, PdfDocu copy.style.border = style.border; copy.style.opacity = style.opacity; (copy as any).marqueeing = true; - copy.className = "pdfViewer-annotationBox"; + copy.className = "pdfViewerDash-annotationBox"; this.createAnnotation(copy, this.getPageFromScroll(this._marqueeY)); } @@ -645,26 +637,29 @@ export class PDFViewer extends ViewBoxAnnotatableComponent<IViewerProps, PdfDocu @action onZoomWheel = (e: React.WheelEvent) => { - e.stopPropagation(); - if (e.ctrlKey) { - const curScale = Number(this._pdfViewer.currentScaleValue); - this._pdfViewer.currentScaleValue = Math.max(1, Math.min(10, curScale - curScale * e.deltaY / 1000)); - this._zoomed = Number(this._pdfViewer.currentScaleValue); + if (this.active()) { + e.stopPropagation(); + if (e.ctrlKey) { + const curScale = Number(this._pdfViewer.currentScaleValue); + this._pdfViewer.currentScaleValue = Math.max(1, Math.min(10, curScale - curScale * e.deltaY / 1000)); + this._zoomed = Number(this._pdfViewer.currentScaleValue); + } } } @computed get annotationLayer() { TraceMobx(); - return <div className="pdfViewer-annotationLayer" style={{ height: NumCast(this.Document._nativeHeight), transform: `scale(${this._zoomed})` }} ref={this._annotationLayer}> - {this.nonDocAnnotations.sort((a, b) => NumCast(a.y) - NumCast(b.y)).map((anno, index) => - <Annotation {...this.props} focus={this.props.focus} dataDoc={this.dataDoc} fieldKey={this.props.fieldKey} anno={anno} key={`${anno[Id]}-annotation`} />)} + return <div className="pdfViewerDash-annotationLayer" style={{ height: NumCast(this.Document._nativeHeight), transform: `scale(${this._zoomed})` }} ref={this._annotationLayer}> + {this.nonDocAnnotations.sort((a, b) => NumCast(a.y) - NumCast(b.y)).map(anno => + <Annotation {...this.props} focus={this.props.focus} dataDoc={this.dataDoc} fieldKey={this.props.fieldKey} anno={anno} key={`${anno[Id]}-annotation`} />) + } </div>; } overlayTransform = () => this.scrollXf().scale(1 / this._zoomed); panelWidth = () => (this.Document.scrollHeight || this.Document._nativeHeight || 0); panelHeight = () => this._pageSizes.length && this._pageSizes[0] ? this._pageSizes[0].width : (this.Document._nativeWidth || 0); @computed get overlayLayer() { - return <div className={`pdfViewer-overlay${Doc.GetSelectedTool() !== InkTool.None || SnappingManager.GetIsDragging() ? "-inking" : ""}`} id="overlay" + return <div className={`pdfViewerDash-overlay${Doc.GetSelectedTool() !== InkTool.None || SnappingManager.GetIsDragging() ? "-inking" : ""}`} id="overlay" style={{ transform: `scale(${this._zoomed})` }}> <CollectionFreeFormView {...this.props} LibraryPath={this.props.ContainingCollectionView?.props.LibraryPath ?? emptyPath} @@ -696,13 +691,13 @@ export class PDFViewer extends ViewBoxAnnotatableComponent<IViewerProps, PdfDocu </div>; } @computed get pdfViewerDiv() { - return <div className={"pdfViewer-text" + ((!DocumentDecorations.Instance.Interacting && (this.props.isSelected() || this.props.isChildActive())) ? "-selected" : "")} ref={this._viewer} />; + return <div className={"pdfViewerDash-text" + ((!DocumentDecorations.Instance?.Interacting && (this.props.isSelected() || this.props.isChildActive())) ? "-selected" : "")} ref={this._viewer} />; } @computed get contentScaling() { return this.props.ContentScaling(); } @computed get standinViews() { return <> {this._showCover ? this.getCoverImage() : (null)} - {this._showWaiting ? <img className="pdfViewer-waiting" key="waiting" src={"/assets/loading.gif"} /> : (null)} + {this._showWaiting ? <img className="pdfViewerDash-waiting" key="waiting" src={"/assets/loading.gif"} /> : (null)} </>; } marqueeWidth = () => this._marqueeWidth; @@ -714,12 +709,12 @@ export class PDFViewer extends ViewBoxAnnotatableComponent<IViewerProps, PdfDocu contentZoom = () => this._zoomed; render() { TraceMobx(); - return <div className={"pdfViewer" + (this.active() ? "-interactive" : "")} ref={this._mainCont} + return <div className={"pdfViewerDash" + (this.active() ? "-interactive" : "")} ref={this._mainCont} onScroll={this.onScroll} onWheel={this.onZoomWheel} onPointerDown={this.onPointerDown} onClick={this.onClick} style={{ overflowX: this._zoomed !== 1 ? "scroll" : undefined, - width: !this.props.Document._fitWidth ? NumCast(this.props.Document._nativeWidth) : `${100 / this.contentScaling}%`, - height: !this.props.Document._fitWidth ? NumCast(this.props.Document._nativeHeight) : `${100 / this.contentScaling}%`, + width: !this.props.Document._fitWidth && (window.screen.width > 600) ? NumCast(this.props.Document._nativeWidth) : `${100 / this.contentScaling}%`, + height: !this.props.Document._fitWidth && (window.screen.width > 600) ? NumCast(this.props.Document._nativeHeight) : `${100 / this.contentScaling}%`, transform: `scale(${this.props.ContentScaling()})` }} > {this.pdfViewerDiv} @@ -742,7 +737,7 @@ interface PdfViewerMarqueeProps { @observer class PdfViewerMarquee extends React.Component<PdfViewerMarqueeProps> { render() { - return !this.props.isMarqueeing() ? (null) : <div className="pdfViewer-dragAnnotationBox" + return !this.props.isMarqueeing() ? (null) : <div className="pdfViewerDash-dragAnnotationBox" style={{ left: `${this.props.x()}px`, top: `${this.props.y()}px`, width: `${this.props.width()}px`, height: `${this.props.height()}px`, @@ -751,4 +746,4 @@ class PdfViewerMarquee extends React.Component<PdfViewerMarqueeProps> { }}> </div>; } -}
\ No newline at end of file +} diff --git a/src/client/views/presentationview/PresElementBox.scss b/src/client/views/presentationview/PresElementBox.scss index ccd2e8947..dbe6b0d4f 100644 --- a/src/client/views/presentationview/PresElementBox.scss +++ b/src/client/views/presentationview/PresElementBox.scss @@ -13,9 +13,10 @@ -moz-user-select: none; -ms-user-select: none; user-select: none; - transition: all .1s; + transition: all .1s; padding: 0px; padding-bottom: 3px; + .documentView-node { position: absolute; z-index: 1; @@ -45,7 +46,7 @@ .presElementBox-closeIcon { border-radius: 20px; - transform:scale(0.7); + transform: scale(0.7); position: absolute; right: 0; top: 0; @@ -58,6 +59,7 @@ position: relative; width: 100%; height: auto; + .presElementBox-interaction { color: gray; float: left; @@ -65,6 +67,7 @@ width: 20px; height: 20px; } + .presElementBox-interaction-selected { color: white; float: left; @@ -76,7 +79,7 @@ } .presElementBox-name { - font-size: 12pxππ; + font-size: 12px; position: absolute; display: inline-block; width: calc(100% - 45px); @@ -90,15 +93,58 @@ display: flex; width: auto; justify-content: center; - margin:auto; + margin: auto; } .presElementBox-embeddedMask { - width:100%; - height:100%; + width: 100%; + height: 100%; position: absolute; - left:0; - top:0; + left: 0; + top: 0; background: transparent; - z-index:2; + z-index: 2; +} + +@media only screen and (max-device-width: 480px) { + .presElementBox-buttons { + display: inline-flex; + position: absolute; + top: 0; + right: 0; + z-index: 3; + width: 50%; + + .presElementBox-interaction { + width: 50; + height: 50; + } + + .presElementBox-interaction-selected { + width: 50; + height: 50; + } + } + + .presElementBox-item { + display: inline-flex; + overflow: hidden; + } + + .presElementBox-closeIcon { + transform: scale(1.5); + right: 10; + top: 10; + } + + .presElementBox-name { + font-size: 30px; + top: 10px; + z-index: 3; + width: 50%; + } + + .presElementBox-embedded { + transform: translate(0, 90px) scale(1.5); + } }
\ No newline at end of file diff --git a/src/client/views/presentationview/PresElementBox.tsx b/src/client/views/presentationview/PresElementBox.tsx index 6b59a0563..6fd3455b6 100644 --- a/src/client/views/presentationview/PresElementBox.tsx +++ b/src/client/views/presentationview/PresElementBox.tsx @@ -49,7 +49,7 @@ export class PresElementBox extends ViewBoxBaseComponent<FieldViewProps, PresDoc componentDidMount() { this._heightDisposer = reaction(() => [this.rootDoc.presExpandInlineButton, this.collapsedHeight], - params => this.layoutDoc._height = NumCast(params[1]) + (Number(params[0]) ? 100 : 0), { fireImmediately: true }); + params => this.layoutDoc._height = NumCast(params[1]) + (Number(params[0]) ? 200 : 0), { fireImmediately: true }); } componentWillUnmount() { this._heightDisposer?.(); diff --git a/src/client/views/search/SearchItem.tsx b/src/client/views/search/SearchItem.tsx index 74262d81a..2436bf418 100644 --- a/src/client/views/search/SearchItem.tsx +++ b/src/client/views/search/SearchItem.tsx @@ -85,7 +85,7 @@ export class SelectorContextMenu extends React.Component<SearchItemProps> { const item = React.createRef<HTMLDivElement>(); return <div className="collection" key={doc.col[Id] + doc.target[Id]} ref={item}> <div className="collection-item" onPointerDown={ - SetupDrag(item, () => doc.col, undefined, undefined, undefined, undefined, () => SearchBox.Instance.closeSearch())}> + SetupDrag(item, () => doc.col, undefined, undefined, () => SearchBox.Instance.closeSearch())}> <FontAwesomeIcon icon={faStickyNote} /> </div> <a onClick={this.getOnClick(doc)}>{doc.col.title}</a> diff --git a/src/fields/DateField.ts b/src/fields/DateField.ts index a925148c2..bee62663e 100644 --- a/src/fields/DateField.ts +++ b/src/fields/DateField.ts @@ -29,6 +29,10 @@ export class DateField extends ObjectField { [ToString]() { return this.date.toISOString(); } + + getDate() { + return this.date; + } } Scripting.addGlobal(function d(...dateArgs: any[]) { diff --git a/src/fields/Doc.ts b/src/fields/Doc.ts index 8c8720179..7aa1d528d 100644 --- a/src/fields/Doc.ts +++ b/src/fields/Doc.ts @@ -96,6 +96,7 @@ export const AclSym = Symbol("Acl"); export const AclPrivate = Symbol("AclOwnerOnly"); export const AclReadonly = Symbol("AclReadOnly"); export const AclAddonly = Symbol("AclAddonly"); +export const AclReadWrite = Symbol("AclReadWrite"); export const UpdatingFromServer = Symbol("UpdatingFromServer"); const CachedUpdates = Symbol("Cached updates"); @@ -113,6 +114,8 @@ export function fetchProto(doc: Doc) { case "addOnly": doc[AclSym] = AclAddonly; break; + case "write": + doc[AclSym] = AclReadWrite; } } @@ -829,12 +832,14 @@ export namespace Doc { })(doc); } export function BrushDoc(doc: Doc) { + if (!doc || doc[AclSym] === AclPrivate || Doc.GetProto(doc)[AclSym] === AclPrivate) return doc; brushManager.BrushedDoc.set(doc, true); brushManager.BrushedDoc.set(Doc.GetProto(doc), true); return doc; } export function UnBrushDoc(doc: Doc) { + if (!doc || doc[AclSym] === AclPrivate || Doc.GetProto(doc)[AclSym] === AclPrivate) return doc; brushManager.BrushedDoc.delete(doc); brushManager.BrushedDoc.delete(Doc.GetProto(doc)); @@ -942,20 +947,27 @@ export namespace Doc { // filters document in a container collection: // all documents with the specified value for the specified key are included/excluded // based on the modifiers :"check", "x", undefined - export function setDocFilter(container: Doc, key: string, value: any, modifiers?: "check" | "x" | undefined) { + export function setDocFilter(container: Doc, key: string, value: any, modifiers?: "match" | "check" | "x" | undefined) { const docFilters = Cast(container._docFilters, listSpec("string"), []); - for (let i = 0; i < docFilters.length; i += 3) { - if (docFilters[i] === key && docFilters[i + 1] === value) { - docFilters.splice(i, 3); - break; + runInAction(() => { + for (let i = 0; i < docFilters.length; i += 3) { + if (docFilters[i] === key && (docFilters[i + 1] === value || modifiers === "match")) { + if (docFilters[i + 2] === modifiers && modifiers && docFilters[i + 1] === value) return; + docFilters.splice(i, 3); + break; + } } - } - if (typeof modifiers === "string") { - docFilters.push(key); - docFilters.push(value); - docFilters.push(modifiers); - container._docFilters = new List<string>(docFilters); - } + if (typeof modifiers === "string") { + if (!docFilters.length && modifiers === "match" && value === undefined) { + container._docFilters = undefined; + } else { + docFilters.push(key); + docFilters.push(value); + docFilters.push(modifiers); + container._docFilters = new List<string>(docFilters); + } + } + }); } export function readDocRangeFilter(doc: Doc, key: string) { const docRangeFilters = Cast(doc._docRangeFilters, listSpec("string"), []); @@ -973,7 +985,7 @@ export namespace Doc { export function toggleNativeDimensions(layoutDoc: Doc, contentScale: number, panelWidth: number, panelHeight: number) { runInAction(() => { if (layoutDoc._nativeWidth || layoutDoc._nativeHeight) { - layoutDoc.scale = NumCast(layoutDoc.scale, 1) * contentScale; + layoutDoc._viewScale = NumCast(layoutDoc._viewScale, 1) * contentScale; layoutDoc._nativeWidth = undefined; layoutDoc._nativeHeight = undefined; } @@ -1159,12 +1171,11 @@ Scripting.addGlobal(function activePresentationItem() { const curPres = Doc.UserDoc().activePresentation as Doc; return curPres && DocListCast(curPres[Doc.LayoutFieldKey(curPres)])[NumCast(curPres._itemIndex)]; }); -Scripting.addGlobal(function selectDoc(doc: any) { Doc.UserDoc().activeSelection = new List([doc]); }); Scripting.addGlobal(function selectedDocs(container: Doc, excludeCollections: boolean, prevValue: any) { const docs = DocListCast(Doc.UserDoc().activeSelection). filter(d => !Doc.AreProtosEqual(d, container) && !d.annotationOn && d.type !== DocumentType.DOCHOLDER && d.type !== DocumentType.KVP && (!excludeCollections || d.type !== DocumentType.COL || !Cast(d.data, listSpec(Doc), null))); return docs.length ? new List(docs) : prevValue; }); -Scripting.addGlobal(function setDocFilter(container: Doc, key: string, value: any, modifiers?: "check" | "x" | undefined) { Doc.setDocFilter(container, key, value, modifiers); }); +Scripting.addGlobal(function setDocFilter(container: Doc, key: string, value: any, modifiers?: "match" | "check" | "x" | undefined) { Doc.setDocFilter(container, key, value, modifiers); }); Scripting.addGlobal(function setDocFilterRange(container: Doc, key: string, range: number[]) { Doc.setDocFilterRange(container, key, range); });
\ No newline at end of file diff --git a/src/fields/InkField.ts b/src/fields/InkField.ts index 51a5768bf..7cfd74cc4 100644 --- a/src/fields/InkField.ts +++ b/src/fields/InkField.ts @@ -1,7 +1,7 @@ import { Deserializable } from "../client/util/SerializationHelper"; import { serializable, custom, createSimpleSchema, list, object, map } from "serializr"; import { ObjectField } from "./ObjectField"; -import { Copy, ToScriptString, ToString } from "./FieldSymbols"; +import { Copy, ToScriptString, ToString, Update } from "./FieldSymbols"; export enum InkTool { None = "none", @@ -31,6 +31,8 @@ const strokeDataSchema = createSimpleSchema({ export class InkField extends ObjectField { @serializable(list(object(strokeDataSchema))) readonly inkData: InkData; + // inkData: InkData; + constructor(data: InkData) { super(); diff --git a/src/fields/List.ts b/src/fields/List.ts index fdabea365..a9da75abb 100644 --- a/src/fields/List.ts +++ b/src/fields/List.ts @@ -291,9 +291,10 @@ class ListImpl<T extends Field> extends ObjectField { this.___fields = value; for (const key in value) { const field = value[key]; - if (!(field instanceof ObjectField)) continue; - (field as ObjectField)[Parent] = this[Self]; - (field as ObjectField)[OnUpdate] = updateFunction(this[Self], key, field, this[SelfProxy]); + if (field instanceof ObjectField) { + field[Parent] = this[Self]; + field[OnUpdate] = updateFunction(this[Self], key, field, this[SelfProxy]); + } } } diff --git a/src/fields/ObjectField.ts b/src/fields/ObjectField.ts index 9aa1c9b04..92b2cfa60 100644 --- a/src/fields/ObjectField.ts +++ b/src/fields/ObjectField.ts @@ -3,8 +3,8 @@ import { OnUpdate, Parent, Copy, ToScriptString, ToString } from "./FieldSymbols import { Scripting } from "../client/util/Scripting"; export abstract class ObjectField { - protected [OnUpdate](diff?: any) { } - private [Parent]?: RefField | ObjectField; + public [OnUpdate](diff?: any) { } + public [Parent]?: RefField | ObjectField; abstract [Copy](): ObjectField; abstract [ToScriptString](): string; diff --git a/src/fields/RichTextUtils.ts b/src/fields/RichTextUtils.ts index 7c7bf3e12..a590c88c4 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.allHrefs.length ? attrs.allHrefs[0].href : ""; + let url = attrs.allLinks.length ? attrs.allLinks[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/fields/Schema.ts b/src/fields/Schema.ts index 72bce283d..98ef3e087 100644 --- a/src/fields/Schema.ts +++ b/src/fields/Schema.ts @@ -65,9 +65,8 @@ export function makeInterface<T extends Interface[]>(...schemas: T): InterfaceFu return obj; }; return function (doc?: Doc | Doc[]) { - doc = doc || new Doc; - if (doc instanceof Doc) { - return fn(doc); + if (doc instanceof Doc || doc === undefined) { + return fn(doc || new Doc); } else { return doc.map(fn); } diff --git a/src/fields/documentSchemas.ts b/src/fields/documentSchemas.ts index 40dadf5a8..97f62c9d4 100644 --- a/src/fields/documentSchemas.ts +++ b/src/fields/documentSchemas.ts @@ -2,6 +2,8 @@ import { makeInterface, createSchema, listSpec } from "./Schema"; import { ScriptField } from "./ScriptField"; import { Doc } from "./Doc"; import { DateField } from "./DateField"; +import { SchemaHeaderField } from "./SchemaHeaderField"; +import { Schema } from "prosemirror-model"; export const documentSchema = createSchema({ // content properties @@ -43,10 +45,16 @@ export const documentSchema = createSchema({ _showTitleHover: "string", // the showTitle should be shown only on hover _showAudio: "boolean", // whether to show the audio record icon on documents _freeformLayoutEngine: "string",// the string ID for the layout engine to use to layout freeform view documents - _LODdisable: "boolean", // whether to disbale LOD switching for CollectionFreeFormViews + _freeformLOD: "boolean", // whether to enable LOD switching for CollectionFreeFormViews _pivotField: "string", // specifies which field key should be used as the timeline/pivot axis _replacedChrome: "string", // what the default chrome is replaced with. Currently only supports the value of 'replaced' for PresBox's. _chromeStatus: "string", // determines the state of the collection chrome. values allowed are 'replaced', 'enabled', 'disabled', 'collapsed' + _columnsFill: "boolean", // whether documents in a stacking view column should be sized to fill the column + _columnsSort: "string", // how a document should be sorted "ascending", "descending", undefined (none) + _columnsStack: "boolean", // whether a stacking document stacks vertically (as opposed to masonry horizontal) + _columnsHideIfEmpty: "boolean", // whether empty stacking view column headings should be hidden + _columnHeaders: listSpec(SchemaHeaderField), // header descriptions for stacking/masonry + _schemaHeaders: listSpec(SchemaHeaderField), // header descriptions for schema views _fontSize: "number", _fontFamily: "string", _sidebarWidthPercent: "string", // percent of text window width taken up by sidebar diff --git a/src/fields/util.ts b/src/fields/util.ts index ad7b6ea7a..2dc21c987 100644 --- a/src/fields/util.ts +++ b/src/fields/util.ts @@ -10,6 +10,7 @@ import { DocServer } from "../client/DocServer"; import { ComputedField } from "./ScriptField"; import { ScriptCast } from "./Types"; + function _readOnlySetter(): never { throw new Error("Documents can't be modified in read-only mode"); } @@ -77,7 +78,7 @@ const _setterImpl = action(function (target: any, prop: string | symbol | number } else { target.__fields[prop] = value; } - if (typeof value === "object" && !(value instanceof ObjectField)) debugger; + //if (typeof value === "object" && !(value instanceof ObjectField)) debugger; if (writeToServer) { if (value === undefined) target[Update]({ '$unset': { ["fields." + prop]: "" } }); else target[Update]({ '$set': { ["fields." + prop]: value instanceof ObjectField ? SerializationHelper.Serialize(value) : (value === undefined ? null : value) } }); @@ -107,10 +108,10 @@ export function OVERRIDE_ACL(val: boolean) { } const layoutProps = ["panX", "panY", "width", "height", "nativeWidth", "nativeHeight", "fitWidth", "fitToBox", - "LODdisable", "chromeStatus", "viewType", "gridGap", "xMargin", "yMargin", "autoHeight"]; + "chromeStatus", "viewType", "gridGap", "xMargin", "yMargin", "autoHeight"]; export function setter(target: any, in_prop: string | symbol | number, value: any, receiver: any): boolean { let prop = in_prop; - if (target[AclSym] && !_overrideAcl) return true; + if (target[AclSym] && !_overrideAcl && !DocServer.PlaygroundFields.includes(in_prop.toString())) return true; if (typeof prop === "string" && prop !== "__id" && prop !== "__fields" && (prop.startsWith("_") || layoutProps.includes(prop))) { if (!prop.startsWith("_")) { console.log(prop + " is deprecated - switch to _" + prop); @@ -155,9 +156,6 @@ export function getter(target: any, in_prop: string | symbol | number, receiver: function getFieldImpl(target: any, prop: string | number, receiver: any, ignoreProto: boolean = false): any { receiver = receiver || target[SelfProxy]; - if (target === undefined) { - console.log(""); - } let field = target.__fields[prop]; for (const plugin of getterPlugins) { const res = plugin(receiver, prop, field); diff --git a/src/mobile/AudioUpload.scss b/src/mobile/AudioUpload.scss new file mode 100644 index 000000000..6e64d9e2e --- /dev/null +++ b/src/mobile/AudioUpload.scss @@ -0,0 +1,61 @@ +@import "../client/views/globalCssVariables.scss"; + +.audioUpload_cont { + display: flex; + justify-content: center; + flex-direction: column; + align-items: center; + margin-top: 10px; + height: 400px; + width: 600px; +} + +.upload_label { + position: relative; + font-weight: 700; + color: black; + background-color: rgba(0, 0, 0, 0); + border: solid 3px black; + margin: 10px; + font-size: 30; + height: 70px; + width: 60%; + display: inline-flex; + font-family: sans-serif; + text-transform: uppercase; + justify-content: center; + flex-direction: column; + border-radius: 10px; +} + +.restart_label { + position: relative; + font-weight: 700; + color: black; + background-color: rgba(0, 0, 0, 0); + border: solid 3px black; + margin: 10px; + font-size: 30; + height: 70px; + width: 60%; + display: inline-flex; + font-family: sans-serif; + text-transform: uppercase; + justify-content: center; + flex-direction: column; + border-radius: 10px; +} + +.audio-upload { + top: 100%; + opacity: 0; +} + +.audio-upload.active { + top: 0; + position: absolute; + z-index: 999; + height: 100vh; + width: 100vw; + opacity: 1; +}
\ No newline at end of file diff --git a/src/mobile/AudioUpload.tsx b/src/mobile/AudioUpload.tsx new file mode 100644 index 000000000..590bf8f9d --- /dev/null +++ b/src/mobile/AudioUpload.tsx @@ -0,0 +1,152 @@ +import { Docs } from '../client/documents/Documents'; +import "./ImageUpload.scss"; +import React = require('react'); +import { observer } from 'mobx-react'; +import { observable, action, computed } from 'mobx'; +import { Utils, emptyPath, returnFalse, emptyFunction, returnOne, returnZero, returnTrue, returnEmptyFilter } from '../Utils'; +import { Doc, Opt } from '../fields/Doc'; +import { Cast, FieldValue } from '../fields/Types'; +import { listSpec } from '../fields/Schema'; +import MainViewModal from '../client/views/MainViewModal'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { nullAudio } from '../fields/URLField'; +import { Transform } from '../client/util/Transform'; +import { DocumentView } from '../client/views/nodes/DocumentView'; +import { MobileInterface } from './MobileInterface'; +import { DictationOverlay } from '../client/views/DictationOverlay'; +import RichTextMenu from '../client/views/nodes/formattedText/RichTextMenu'; +import { ContextMenu } from '../client/views/ContextMenu'; + +@observer +export class AudioUpload extends React.Component { + @observable public _audioCol: Doc = FieldValue(Cast(Docs.Create.FreeformDocument([Cast(Docs.Create.AudioDocument(nullAudio, { title: "mobile audio", _width: 500, _height: 100 }), Doc) as Doc], { title: "mobile audio", _width: 300, _height: 300, _fitToBox: true, boxShadow: "0 0" }), Doc)) as Doc; + + /** + * Handles the onclick functionality for the 'Restart' button + * Resets the document to its default view + */ + @action + clearUpload = () => { + for (let i = 1; i < 8; i++) { + this.setOpacity(i, "0.2"); + } + this._audioCol = FieldValue(Cast( + Docs.Create.FreeformDocument( + [Cast(Docs.Create.AudioDocument(nullAudio, { + title: "mobile audio", + _width: 500, + _height: 100 + }), Doc) as Doc], { title: "mobile audio", _width: 300, _height: 300, _fitToBox: true, boxShadow: "0 0" }), Doc)) as Doc; + } + + /** + * Handles the onClick of the 'Close' button + * Reset upload interface and toggle audio + */ + closeUpload = () => { + this.clearUpload(); + MobileInterface.Instance.toggleAudio(); + } + + /** + * Handles the on click of the 'Upload' button. + * 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._audioCol; + const data = Cast(audioRightSidebar.data, listSpec(Doc)); + for (let i = 1; i < 8; i++) { + setTimeout(() => this.setOpacity(i, "1"), i * 200); + } + if (data) { + data.push(audioDoc); + } + // Resets uploader after 3 seconds + setTimeout(this.clearUpload, 3000); + } + + // Returns the upload audio menu + private get uploadInterface() { + return ( + <> + <ContextMenu /> + <DictationOverlay /> + <div style={{ display: "none" }}><RichTextMenu key="rich" /></div> + <div className="closeUpload" onClick={() => this.closeUpload()}> + <FontAwesomeIcon icon="window-close" size={"lg"} /> + </div> + <FontAwesomeIcon icon="microphone" size="lg" style={{ fontSize: "130" }} /> + <div className="audioUpload_cont"> + <DocumentView + Document={this._audioCol} + DataDoc={undefined} + LibraryPath={emptyPath} + addDocument={undefined} + addDocTab={returnFalse} + pinToPres={emptyFunction} + rootSelected={returnTrue} + removeDocument={undefined} + docFilters={returnEmptyFilter} + onClick={undefined} + ScreenToLocalTransform={Transform.Identity} + ContentScaling={returnOne} + PanelWidth={() => 600} + PanelHeight={() => 400} + NativeHeight={returnZero} + NativeWidth={returnZero} + renderDepth={0} + focus={emptyFunction} + backgroundColor={() => "rgba(0,0,0,0)"} + parentActive={returnTrue} + whenActiveChanged={emptyFunction} + bringToFront={emptyFunction} + ContainingCollectionView={undefined} + ContainingCollectionDoc={undefined} + /> + </div> + <div className="restart_label" onClick={this.clearUpload}> + Restart + </div> + <div className="upload_label" onClick={this.uploadAudio}> + Upload + </div> + <div className="loadingImage"> + <div className="loadingSlab" id="slab01" /> + <div className="loadingSlab" id="slab02" /> + <div className="loadingSlab" id="slab03" /> + <div className="loadingSlab" id="slab04" /> + <div className="loadingSlab" id="slab05" /> + <div className="loadingSlab" id="slab06" /> + <div className="loadingSlab" id="slab07" /> + </div> + </> + ); + } + + // Handles the setting of the loading bar + setOpacity = (index: number, opacity: string) => { + const slab = document.getElementById("slab0" + index); + if (slab) { + slab.style.opacity = opacity; + } + } + + @observable private dialogueBoxOpacity = 1; + @observable private overlayOpacity = 0.4; + + render() { + return ( + <MainViewModal + contents={this.uploadInterface} + isDisplayed={true} + interactive={true} + dialogueBoxDisplayedOpacity={this.dialogueBoxOpacity} + overlayDisplayedOpacity={this.overlayOpacity} + /> + ); + } + +} + + diff --git a/src/mobile/ImageUpload.scss b/src/mobile/ImageUpload.scss index eea69b81c..890258918 100644 --- a/src/mobile/ImageUpload.scss +++ b/src/mobile/ImageUpload.scss @@ -5,8 +5,32 @@ justify-content: center; flex-direction: column; align-items: center; - width: 100vw; - height: 100vh; + max-width: 400px; + min-width: 400px; + + .upload_label { + font-weight: 700; + color: black; + background-color: rgba(0, 0, 0, 0); + border: solid 3px black; + margin: 10px; + font-size: 30; + height: 70px; + width: 80%; + display: flex; + font-family: sans-serif; + text-transform: uppercase; + justify-content: center; + flex-direction: column; + border-radius: 10px; + } + + .file { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + direction: ltr; + } .button_file { text-align: center; @@ -17,18 +41,98 @@ font-size: 3em; } - .input_file { - display: none; + .inputfile { + width: 0.1px; + height: 0.1px; + opacity: 0; + overflow: hidden; + position: absolute; + z-index: -1; } - .upload_label, - .upload_button { - background: $dark-color; - font-size: 500%; - font-family: $sans-serif; - text-align: center; - padding: 5vh; - margin-bottom: 20px; - color: white; + .inputfile+label { + font-weight: 700; + color: black; + background-color: rgba(0, 0, 0, 0); + border: solid 3px black; + margin: 10px; + font-size: 30; + height: 70px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + margin-top: 30px; + width: 80%; + display: flex; + font-family: sans-serif; + text-transform: uppercase; + justify-content: center; + flex-direction: column; + border-radius: 10px; + } + + .inputfile.active+label { + font-style: italic; + color: black; + background-color: lightgreen; + border: solid 3px darkgreen; + } + + .status { + font-size: 2em; } + +} + +.image-upload { + top: 100%; + opacity: 0; +} + +.image-upload.active { + top: 0; + position: absolute; + z-index: 999; + height: 100vh; + width: 100vw; + opacity: 1; +} + +.uploadContainer { + top: 40; + position: absolute; + z-index: 1000; + height: 20vh; + width: 80vw; + opacity: 1; +} + +.closeUpload { + position: absolute; + border-radius: 10px; + top: 3; + color: black; + font-size: 30; + right: 3; + z-index: 1002; + padding: 0px 3px; + background: rgba(0, 0, 0, 0); + transition: 0.5s ease all; + border: 0px solid; +} + +.loadingImage { + display: inline-flex; + width: max-content; +} + +.loadingSlab { + position: relative; + width: 30px; + height: 30px; + margin: 10; + border-radius: 20px; + opacity: 0.2; + background-color: black; + transition: all 2s, opacity 1.5s; }
\ No newline at end of file diff --git a/src/mobile/ImageUpload.tsx b/src/mobile/ImageUpload.tsx index b15042f9f..5ea626d52 100644 --- a/src/mobile/ImageUpload.tsx +++ b/src/mobile/ImageUpload.tsx @@ -1,128 +1,179 @@ -import * as ReactDOM from 'react-dom'; import * as rp from 'request-promise'; import { Docs } from '../client/documents/Documents'; import "./ImageUpload.scss"; import React = require('react'); import { DocServer } from '../client/DocServer'; -import { Opt, Doc } from '../fields/Doc'; +import { observer } from 'mobx-react'; +import { observable, action } from 'mobx'; +import { Utils } from '../Utils'; +import { Networking } from '../client/Network'; +import { Doc, Opt } from '../fields/Doc'; import { Cast } from '../fields/Types'; import { listSpec } from '../fields/Schema'; import { List } from '../fields/List'; -import { observer } from 'mobx-react'; -import { observable } from 'mobx'; -import { Utils } from '../Utils'; -import MobileInterface from './MobileInterface'; -import { CurrentUserUtils } from '../client/util/CurrentUserUtils'; -import { resolvedPorts } from '../client/views/Main'; +import MainViewModal from '../client/views/MainViewModal'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { MobileInterface } from './MobileInterface'; + +export interface ImageUploadProps { + Document: Doc; // Target document for upload (upload location) +} -// const onPointerDown = (e: React.TouchEvent) => { -// let imgInput = document.getElementById("input_image_file"); -// if (imgInput) { -// imgInput.click(); -// } -// } const inputRef = React.createRef<HTMLInputElement>(); @observer -class Uploader extends React.Component { +export class Uploader extends React.Component<ImageUploadProps> { @observable error: string = ""; - @observable status: string = ""; + @observable nm: string = "Choose files"; // Text of 'Choose Files' button + @observable process: string = ""; // Current status of upload onClick = async () => { - console.log("uploader click"); try { - this.status = "initializing protos"; + const col = this.props.Document; await Docs.Prototypes.initialize(); const imgPrev = document.getElementById("img_preview"); + this.setOpacity(1, "1"); // Slab 1 if (imgPrev) { const files: FileList | null = inputRef.current!.files; + this.setOpacity(2, "1"); // Slab 2 if (files && files.length !== 0) { - console.log(files[0]); - const name = files[0].name; - const formData = new FormData(); - formData.append("file", files[0]); - - const upload = window.location.origin + "/uploadFormData"; - this.status = "uploading image"; - console.log("uploading image", formData); - const res = await fetch(upload, { - method: 'POST', - body: formData - }); - this.status = "upload image, getting json"; - const json = await res.json(); - json.map(async (file: any) => { - const path = window.location.origin + file; - const doc = Docs.Create.ImageDocument(path, { _nativeWidth: 200, _width: 200, title: name }); - - this.status = "getting user document"; - - const res = await rp.get(Utils.prepend("/getUserDocumentId")); - if (!res) { - throw new Error("No user id returned"); - } - const field = await DocServer.GetRefField(res); - let pending: Opt<Doc>; - if (field instanceof Doc) { - pending = await Cast(field.rightSidebarCollection, Doc); - } - if (pending) { - this.status = "has pending docs"; - const data = await Cast(pending.data, listSpec(Doc)); - if (data) { - data.push(doc); + this.process = "Uploading Files"; + for (let index = 0; index < files.length; ++index) { + const file = files[index]; + const res = await Networking.UploadFilesToServer(file); + this.setOpacity(3, "1"); // Slab 3 + // For each item that the user has selected + res.map(async ({ result }) => { + const name = file.name; + if (result instanceof Error) { + return; + } + const path = Utils.prepend(result.accessPaths.agnostic.client); + let doc = null; + // Case 1: File is a video + if (file.type === "video/mp4") { + doc = Docs.Create.VideoDocument(path, { _nativeWidth: 400, _width: 400, title: name }); + // Case 2: File is a PDF document + } else if (file.type === "application/pdf") { + doc = Docs.Create.PdfDocument(path, { _nativeWidth: 400, _width: 400, title: name }); + // Case 3: File is another document type (most likely Image) } else { - pending.data = new List([doc]); + doc = Docs.Create.ImageDocument(path, { _nativeWidth: 400, _width: 400, title: name }); } - this.status = "finished"; - } - }); - - // console.log(window.location.origin + file[0]) - - //imgPrev.setAttribute("src", window.location.origin + files[0].name) + this.setOpacity(4, "1"); // Slab 4 + const res = await rp.get(Utils.prepend("/getUserDocumentId")); + if (!res) { + throw new Error("No user id returned"); + } + const field = await DocServer.GetRefField(res); + let pending: Opt<Doc>; + if (field instanceof Doc) { + pending = col; + } + if (pending) { + const data = await Cast(pending.data, listSpec(Doc)); + if (data) data.push(doc); + else pending.data = new List([doc]); + this.setOpacity(5, "1"); // Slab 5 + this.process = "File " + (index + 1).toString() + " Uploaded"; + this.setOpacity(6, "1"); // Slab 6 + } + if ((index + 1) === files.length) { + this.process = "Uploads Completed"; + this.setOpacity(7, "1"); // Slab 7 + } + }); + } + // Case in which the user pressed upload and no files were selected + } else { + this.process = "No file selected"; } + // Three seconds after upload the menu will reset + setTimeout(this.clearUpload, 3000); } } catch (error) { this.error = JSON.stringify(error); } } - render() { + // Updates label after a files is selected (so user knows a file is uploaded) + inputLabel = async () => { + const files: FileList | null = inputRef.current!.files; + await files; + if (files && files.length === 1) { + this.nm = files[0].name; + } else if (files && files.length > 1) { + this.nm = files.length.toString() + " files selected"; + } + } + + // Loops through load icons, and resets buttons + @action + clearUpload = () => { + for (let i = 1; i < 8; i++) { + this.setOpacity(i, "0.2"); + } + this.nm = "Choose files"; + + if (inputRef.current) { + inputRef.current.value = ""; + } + this.process = ""; + } + + // Clears the upload and closes the upload menu + closeUpload = () => { + this.clearUpload(); + MobileInterface.Instance.toggleUpload(); + } + + // Handles the setting of the loading bar + setOpacity = (index: number, opacity: string) => { + const slab = document.getElementById("slab" + index); + if (slab) slab.style.opacity = opacity; + } + + // Returns the upload interface for mobile + private get uploadInterface() { return ( <div className="imgupload_cont"> - <label htmlFor="input_image_file" className="upload_label">Choose an Image</label> - <input type="file" accept="image/*" className="input_file" id="input_image_file" ref={inputRef}></input> - <button onClick={this.onClick} className="upload_button">Upload</button> + <div className="closeUpload" onClick={() => this.closeUpload()}> + <FontAwesomeIcon icon="window-close" size={"lg"} /> + </div> + <FontAwesomeIcon icon="upload" size="lg" style={{ fontSize: "130" }} /> + <input type="file" accept="application/pdf, video/*,image/*" className={`inputFile ${this.nm !== "Choose files" ? "active" : ""}`} id="input_image_file" ref={inputRef} onChange={this.inputLabel} multiple></input> + <label className="file" id="label" htmlFor="input_image_file">{this.nm}</label> + <div className="upload_label" onClick={this.onClick}> + Upload + </div> <img id="img_preview" src=""></img> - <p>{this.status}</p> - <p>{this.error}</p> + <div className="loadingImage"> + <div className="loadingSlab" id="slab1" /> + <div className="loadingSlab" id="slab2" /> + <div className="loadingSlab" id="slab3" /> + <div className="loadingSlab" id="slab4" /> + <div className="loadingSlab" id="slab5" /> + <div className="loadingSlab" id="slab6" /> + <div className="loadingSlab" id="slab7" /> + </div> + <p className="status">{this.process}</p> </div> ); } -} + @observable private dialogueBoxOpacity = 1; + @observable private overlayOpacity = 0.4; - -// DocServer.init(window.location.protocol, window.location.hostname, resolvedPorts.socket, "image upload"); -(async () => { - const info = await CurrentUserUtils.loadCurrentUser(); - DocServer.init(window.location.protocol, window.location.hostname, resolvedPorts.socket, info.email + "mobile"); - await Docs.Prototypes.initialize(); - if (info.id !== "__guest__") { - // a guest will not have an id registered - await CurrentUserUtils.loadUserDocument(info); + render() { + return ( + <MainViewModal + contents={this.uploadInterface} + isDisplayed={true} + interactive={true} + dialogueBoxDisplayedOpacity={this.dialogueBoxOpacity} + overlayDisplayedOpacity={this.overlayOpacity} + /> + ); } - document.getElementById('root')!.addEventListener('wheel', event => { - if (event.ctrlKey) { - event.preventDefault(); - } - }, true); - ReactDOM.render(( - // <Uploader /> - <MobileInterface /> - ), - document.getElementById('root') - ); + } -)();
\ No newline at end of file diff --git a/src/mobile/MobileInkOverlay.tsx b/src/mobile/MobileInkOverlay.tsx index 59c73ed27..d668d134e 100644 --- a/src/mobile/MobileInkOverlay.tsx +++ b/src/mobile/MobileInkOverlay.tsx @@ -4,11 +4,9 @@ import { MobileInkOverlayContent, GestureContent, UpdateMobileInkOverlayPosition import { observable, action } from "mobx"; import { GestureUtils } from "../pen-gestures/GestureUtils"; import "./MobileInkOverlay.scss"; -import { StrCast, Cast } from '../fields/Types'; import { DragManager } from "../client/util/DragManager"; import { DocServer } from '../client/DocServer'; -import { Doc, DocListCastAsync } from '../fields/Doc'; -import { listSpec } from '../fields/Schema'; +import { Doc } from '../fields/Doc'; @observer diff --git a/src/mobile/MobileInterface.scss b/src/mobile/MobileInterface.scss index 4d86e208f..4b32c3da0 100644 --- a/src/mobile/MobileInterface.scss +++ b/src/mobile/MobileInterface.scss @@ -1,19 +1,445 @@ -.mobileInterface-inkInterfaceButtons { - position: absolute; +$navbar-height: 120px; +$pathbar-height: 50px; + +@media only screen and (max-device-width: 480px) { + * { + margin: 0px; + padding: 0px; + box-sizing: border-box; + font-family: sans-serif; + } +} + +body { + overflow: hidden; +} + +.mobileInterface-container { + height: 100%; + position: relative; + touch-action: none; + width: 100%; + + -webkit-touch-callout: none; + -webkit-user-select: none; + -khtml-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + -webkit-tap-highlight-color: rgba(0, 0, 0, 0); +} + +// Topbar of Dash Mobile +.navbar { + position: fixed; top: 0px; + left: 0px; + width: 100vw; + height: $navbar-height; + background-color: whitesmoke; + z-index: 150; + + .cover { + position: absolute; + right: 0px; + top: 0px; + height: 120px; + width: 120px; + background-color: whitesmoke; + z-index: 200; + } + + .toggle-btn { + position: absolute; + right: 20px; + top: 30px; + height: 70px; + width: 70px; + transition: all 400ms ease-in-out 200ms; + z-index: 180; + } + + .background { + position: absolute; + right: 0px; + top: 0px; + height: 120px; + width: 120px; + //border: 1px solid black; + } + + .background.active { + background-color: lightgrey; + } + + .toggle-btn-home { + right: -200px; + } + + .header { + position: absolute; + top: 50%; + top: calc(9px + 50%); + right: 50%; + transform: translate(50%, -50%); + font-size: 40; + font-weight: 700; + text-align: center; + user-select: none; + text-transform: uppercase; + font-family: Arial, Helvetica, sans-serif; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + direction: ltr; + width: 600px; + } + + .toggle-btn span { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + width: 70%; + height: 4px; + background: black; + transition: all 200ms ease; + z-index: 180; + } + + .toggle-btn span:nth-child(1) { + transition: top 200ms ease-in-out; + top: 30%; + } + + .toggle-btn span:nth-child(3) { + transition: top 200ms ease-in-out; + top: 70%; + } + + .toggle-btn.active { + transition: transform 200ms ease-in-out 200ms; + transform: rotate(135deg); + } + + .toggle-btn.active span:nth-child(1) { + top: 50%; + } + + .toggle-btn.active span:nth-child(2) { + transform: translate(-50%, -50%) rotate(90deg); + } + + .toggle-btn.active span:nth-child(3) { + top: 50%; + } +} + +.sidebar { + position: fixed; + top: 120px; + opacity: 0; + right: -100%; + width: 80%; + height: calc(80% - (120px)); + z-index: 101; + background-color: whitesmoke; + transition: all 400ms ease 50ms; + padding: 20px; + box-shadow: 0 0 5px 5px grey; + + .item { + width: 100%; + padding: 13px 12px; + border-bottom: 1px solid rgba(200, 200, 200, 0.7); + font-family: Arial, Helvetica, sans-serif; + font-style: normal; + font-weight: normal; + user-select: none; + display: inline-flex; + font-size: 35px; + text-transform: uppercase; + color: black; + } + + .ink:focus { + outline: 1px solid blue; + } + + .sidebarButtons { + top: 80px; + position: relative; + } +} + + + + + + +.blanket { + position: fixed; + top: 120px; + opacity: 0.5; + right: -100%; + width: 100%; + height: calc(100% - (120px)); + z-index: 101; + background-color: grey; + padding: 20px; +} + +.blanket.active { + position: absolute; + right: 0%; + z-index: 100; +} + +.home { + position: absolute; + top: 30px; + left: 30px; + font-size: 60; + user-select: none; + text-transform: uppercase; + font-family: Arial, Helvetica, sans-serif; + z-index: 200; +} + +.item-type { + display: inline; + text-transform: lowercase; + margin-left: 20px; + font-size: 35px; + font-style: italic; + color: rgb(28, 28, 28); +} + +.item-title { + max-width: 70%; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.right { + margin-left: 20px; + z-index: 200; +} + +.open { + right: 20px; + font-size: 35; + position: absolute; +} + +.left { + width: 100%; + height: 100%; +} + + + +.sidebar.active { + position: absolute; + right: 0%; + opacity: 1; + z-index: 101; +} + +.back { + position: absolute; + left: 42px; + top: 0; + background: #1a1a1a; + width: 50px; + height: 100%; display: flex; - justify-content: space-between; + justify-content: center; + text-align: center; + flex-direction: column; + align-items: center; + border-radius: 10px; + font-size: 25px; + user-select: none; + z-index: 100; +} + +.pathbar { + position: fixed; + top: 118px; + left: 0px; + background: #1a1a1a; + z-index: 120; + border-radius: 0px; width: 100%; - z-index: 9999; - height: 50px; + height: 80px; + overflow: hidden; + + .pathname { + position: relative; + font-size: 25; + top: 50%; + width: 86%; + left: 12%; + color: whitesmoke; + transform: translate(0%, -50%); + z-index: 20; + font-family: sans-serif; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + direction: rtl; + text-align: left; + text-transform: uppercase; + } + + .scrollmenu { + overflow: auto; + width: 100%; + height: 100%; + white-space: nowrap; + display: inline-flex; + } - .mobileInterface-button { + .hidePath { + position: absolute; height: 100%; + width: 200px; + left: 0px; + top: 0px; + background-image: linear-gradient(to right, #1a1a1a, rgba(0, 0, 0, 0)); + text-align: center; + user-select: none; + z-index: 99; + pointer-events: none; + } + + .pathbarItem { + position: relative; + display: flex; + align-items: center; + color: whitesmoke; + text-align: center; + justify-content: center; + user-select: none; + transform: translate(100px, 0px); + font-size: 30px; + padding: 10px; + text-transform: uppercase; + + .pathbarText { + font-family: sans-serif; + text-align: center; + height: 50px; + padding: 10px; + font-size: 30px; + border-radius: 10px; + text-transform: uppercase; + margin-left: 20px; + position: relative; + } + + .pathIcon { + transform: translate(0px, 0px); + position: relative; + } } } -.mobileInterface-container { - height: 100%; + +/** +* docButton appears at the bottom of mobile document +* Buttons include: pin to presentation, download, upload, reload +*/ +.docButton { position: relative; - touch-action: none; + width: 100px; + display: flex; + height: 100px; + font-size: 70px; + text-align: center; + border: 3px solid black; + margin: 20px; + z-index: 100; + border-radius: 100%; + justify-content: center; + flex-direction: column; + align-items: center; +} + +.docButtonContainer { + top: 80%; + position: absolute; + display: flex; + transform: translate(-50%, 0); + left: 50%; + z-index: 100; +} + +.toolbar { + left: 50%; + transform: translate(-50%); + position: absolute; + height: max-content; + top: 0px; + border-radius: 20px; + background-color: lightgrey; + opacity: 0; + transition: all 400ms ease 50ms; +} + +.toolbar.active { + display: inline-block; + width: 300px; + padding: 5px; + opacity: 1; + height: max-content; + top: -450px; +} + +.colorSelector { + position: absolute; + top: 550px; + left: 280px; + transform: translate(-50%, 0); + z-index: 100; + display: inline-flex; + width: max-content; + height: max-content; + pointer-events: all; + font-size: 80px; + user-select: none; +} + +// Menu buttons for toggling between list and icon view +.homeSwitch { + position: fixed; + top: 212; + right: 36px; + display: inline-flex; + width: max-content; + z-index: 99; + height: 70px; + + .list { + width: 70px; + height: 70px; + margin: 5; + padding: 10; + align-items: center; + text-align: center; + font-size: 50; + border-style: solid; + border-width: 3; + border-color: black; + background: whitesmoke; + align-self: center; + border-radius: 10px; + } + + .list.active { + color: darkred; + border-color: darkred; + } }
\ No newline at end of file diff --git a/src/mobile/MobileInterface.tsx b/src/mobile/MobileInterface.tsx index a50ec103e..fafa94a11 100644 --- a/src/mobile/MobileInterface.tsx +++ b/src/mobile/MobileInterface.tsx @@ -1,47 +1,69 @@ -import React = require('react'); +import * as React from "react"; import { library } from '@fortawesome/fontawesome-svg-core'; -import { faEraser, faHighlighter, faLongArrowAltLeft, faMousePointer, faPenNib } from '@fortawesome/free-solid-svg-icons'; +import { + faTasks, faReply, faQuoteLeft, faHandPointLeft, faFolderOpen, faAngleDoubleLeft, faExternalLinkSquareAlt, faMobile, faThLarge, faWindowClose, faEdit, faTrashAlt, faPalette, faAngleRight, faBell, faTrash, faCamera, faExpand, faCaretDown, faCaretLeft, faCaretRight, faCaretSquareDown, faCaretSquareRight, faArrowsAltH, faPlus, faMinus, + faTerminal, faToggleOn, faFile as fileSolid, faExternalLinkAlt, faLocationArrow, faSearch, faFileDownload, faStop, faCalculator, faWindowMaximize, faAddressCard, + faQuestionCircle, faArrowLeft, faArrowRight, faArrowDown, faArrowUp, faBolt, faBullseye, faCaretUp, faCat, faCheck, faChevronRight, faClipboard, faClone, faCloudUploadAlt, + faCommentAlt, faCompressArrowsAlt, faCut, faEllipsisV, faEraser, faExclamation, faFileAlt, faFileAudio, faFilePdf, faFilm, faFilter, faFont, faGlobeAsia, faHighlighter, + faLongArrowAltRight, faMicrophone, faMousePointer, faMusic, faObjectGroup, faPause, faPen, faPenNib, faPhone, faPlay, faPortrait, faRedoAlt, faStamp, faStickyNote, + faThumbtack, faTree, faTv, faBook, faUndoAlt, faVideo, faAsterisk, faBrain, faImage, faPaintBrush, faTimes, faEye, faHome, faLongArrowAltLeft, faBars, faTh, faChevronLeft, + faAlignRight, faAlignLeft +} from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { action, computed, observable } from 'mobx'; +import { action, computed, observable, reaction, trace, runInAction } from 'mobx'; import { observer } from 'mobx-react'; -import { DocServer } from '../client/DocServer'; -import { Docs } from '../client/documents/Documents'; -import { DocumentManager } from '../client/util/DocumentManager'; -import RichTextMenu from '../client/views/nodes/formattedText/RichTextMenu'; +import { Doc, DocListCast } from '../fields/Doc'; +import { CurrentUserUtils } from '../client/util/CurrentUserUtils'; +import { emptyFunction, emptyPath, returnFalse, returnOne, returnTrue, returnZero, returnEmptyFilter } from '../Utils'; +import { Docs, DocumentOptions } from '../client/documents/Documents'; import { Scripting } from '../client/util/Scripting'; -import { Transform } from '../client/util/Transform'; -import { DocumentDecorations } from '../client/views/DocumentDecorations'; -import GestureOverlay from '../client/views/GestureOverlay'; import { DocumentView } from '../client/views/nodes/DocumentView'; -import { RadialMenu } from '../client/views/nodes/RadialMenu'; -import { PreviewCursor } from '../client/views/PreviewCursor'; -import { Doc, DocListCast, FieldResult } from '../fields/Doc'; -import { Id } from '../fields/FieldSymbols'; +import { Transform } from '../client/util/Transform'; +import "./MobileInterface.scss"; +import "./ImageUpload.scss"; +import "./AudioUpload.scss"; +import SettingsManager from '../client/util/SettingsManager'; +import { Uploader } from "./ImageUpload"; +import { DockedFrameRenderer } from '../client/views/collections/CollectionDockingView'; import { InkTool } from '../fields/InkField'; -import { listSpec } from '../fields/Schema'; +import GestureOverlay from "../client/views/GestureOverlay"; +import { ScriptField } from "../fields/ScriptField"; +import InkOptionsMenu from "../client/views/collections/collectionFreeForm/InkOptionsMenu"; +import { RadialMenu } from "../client/views/nodes/RadialMenu"; +import { UndoManager } from "../client/util/UndoManager"; +import { List } from "../fields/List"; +import { AudioUpload } from "./AudioUpload"; import { Cast, FieldValue } from '../fields/Types'; -import { WebField } from "../fields/URLField"; -import { CurrentUserUtils } from '../client/util/CurrentUserUtils'; -import { emptyFunction, emptyPath, returnEmptyString, returnFalse, returnOne, returnTrue, returnZero, returnEmptyFilter } from '../Utils'; -import "./MobileInterface.scss"; -import { CollectionView } from '../client/views/collections/CollectionView'; -import { InkingStroke } from '../client/views/InkingStroke'; +import RichTextMenu from "../client/views/nodes/formattedText/RichTextMenu"; +import { AudioBox } from "../client/views/nodes/AudioBox"; +import { CollectionViewType } from "../client/views/collections/CollectionView"; +import { DocumentType } from "../client/documents/DocumentTypes"; -library.add(faLongArrowAltLeft); +library.add(faTasks, faReply, faQuoteLeft, faHandPointLeft, faFolderOpen, faAngleDoubleLeft, faExternalLinkSquareAlt, 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, + faQuestionCircle, faArrowLeft, faArrowRight, faArrowDown, faArrowUp, faBolt, faBullseye, faCaretUp, faCat, faCheck, faChevronRight, faClipboard, faClone, faCloudUploadAlt, + faCommentAlt, faCompressArrowsAlt, faCut, faEllipsisV, faEraser, faExclamation, faFileAlt, faFileAudio, faFilePdf, faFilm, faFilter, faFont, faGlobeAsia, faHighlighter, + faLongArrowAltRight, faMicrophone, faMousePointer, faMusic, faObjectGroup, faPause, faPen, faPenNib, faPhone, faPlay, faPortrait, faRedoAlt, faStamp, faStickyNote, + faThumbtack, faTree, faTv, faUndoAlt, faBook, faVideo, faAsterisk, faBrain, faImage, faPaintBrush, faTimes, faEye, faHome, faLongArrowAltLeft, faBars, faTh, faChevronLeft, + faAlignLeft, faAlignRight); @observer -export default class MobileInterface extends React.Component { - @observable static Instance: MobileInterface; - @computed private get userDoc() { return Doc.UserDoc(); } - @computed private get mainContainer() { return this.userDoc ? FieldValue(Cast(this.userDoc.activeMobile, Doc)) : CurrentUserUtils.GuestMobile; } - // @observable private currentView: "main" | "ink" | "upload" = "main"; - private mainDoc: any = CurrentUserUtils.setupMobileDoc(this.userDoc); - @observable private renderView?: () => JSX.Element; +export class MobileInterface extends React.Component { + static Instance: MobileInterface; + private _library: Doc = CurrentUserUtils.setupLibrary(Doc.UserDoc()); // to access documents in Dash Web + private _mainDoc: any = CurrentUserUtils.setupActiveMobileMenu(Doc.UserDoc()); + @observable private _sidebarActive: boolean = false; //to toggle sidebar display + @observable private _imageUploadActive: boolean = false; //to toggle image upload + @observable private _audioUploadActive: boolean = false; + @observable private _menuListView: boolean = false; //to switch between menu view (list / icon) + @observable private _ink: boolean = false; //toggle whether ink is being dispalyed + @observable private _homeMenu: boolean = true; // to determine whether currently at home menu + @observable private _child: Doc | null = null; // currently selected document + @observable private _activeDoc: Doc = this._mainDoc; // doc updated as the active mobile page is updated (initially home menu) + @observable private _homeDoc: Doc = this._mainDoc; // home menu as a document + @observable private _parents: Array<Doc> = []; // array of parent docs (for pathbar) - // private inkDoc?: Doc; - public drawingInk: boolean = false; - - // private uploadDoc?: Doc; + @computed private get mainContainer() { return Doc.UserDoc() ? FieldValue(Cast(Doc.UserDoc().activeMobile, Doc)) : CurrentUserUtils.GuestMobile; } constructor(props: Readonly<{}>) { super(props); @@ -50,298 +72,613 @@ export default class MobileInterface extends React.Component { @action componentDidMount = () => { - library.add(...[faPenNib, faHighlighter, faEraser, faMousePointer]); + // if the home menu is in list view -> adjust the menu toggle appropriately + this._menuListView = this._homeDoc._viewType === "stacking" ? true : false; + Doc.SetSelectedTool(InkTool.None); // ink should intially be set to none + Doc.UserDoc().activeMobile = this._homeDoc; // active mobile set to home + AudioBox.Enabled = true; - if (this.userDoc && !this.mainContainer) { - this.userDoc.activeMobile = this.mainDoc; - } + // remove double click to avoid mobile zoom in + document.removeEventListener("dblclick", this.onReactDoubleClick); + document.addEventListener("dblclick", this.onReactDoubleClick); } @action - switchCurrentView = (doc: (userDoc: Doc) => Doc, renderView?: () => JSX.Element, onSwitch?: () => void) => { - if (!this.userDoc) return; + componentWillUnmount = () => { + document.removeEventListener('dblclick', this.onReactDoubleClick); + } + + // Prevent zooming in when double tapping the screen + onReactDoubleClick = (e: MouseEvent) => { + e.stopPropagation(); + } - this.userDoc.activeMobile = doc(this.userDoc); - onSwitch && onSwitch(); + // Switch the mobile view to the given doc + @action + switchCurrentView = (doc: Doc, renderView?: () => JSX.Element, onSwitch?: () => void) => { + if (!Doc.UserDoc()) return; + if (this._activeDoc === this._homeDoc) { + this._parents.push(this._activeDoc); + this._homeMenu = false; + } + this._activeDoc = doc; + Doc.UserDoc().activeMobile = doc; + onSwitch?.(); - this.renderView = renderView; + // Ensures that switching to home is not registed + UndoManager.undoStack.length = 0; + UndoManager.redoStack.length = 0; } - onSwitchInking = () => { - Doc.SetSelectedTool(InkTool.Pen); - MobileInterface.Instance.drawingInk = true; + // For toggling the hamburger menu + @action + toggleSidebar = () => { + this._sidebarActive = !this._sidebarActive; - DocServer.Mobile.dispatchOverlayTrigger({ - enableOverlay: true, - width: window.innerWidth, - height: window.innerHeight - }); + if (this._ink) { + this.onSwitchInking(); + } + } + /** + * Method called when 'Library' button is pressed on the home screen + */ + switchToLibrary = async () => { + this.switchCurrentView(this._library); + runInAction(() => this._homeMenu = false); + this.toggleSidebar(); } - onSwitchUpload = async () => { - let width = 300; - let height = 300; - - // get width and height of the collection doc - if (this.mainContainer) { - const data = Cast(this.mainContainer.data, listSpec(Doc)); - if (data) { - const collectionDoc = await data[1]; // this should be the collection doc since the positions should be locked - const docView = DocumentManager.Instance.getDocumentView(collectionDoc); - if (docView) { - width = docView.nativeWidth ? docView.nativeWidth : 300; - height = docView.nativeHeight ? docView.nativeHeight : 300; - } - } + /** + * Back method for navigating through items + */ + @action + back = () => { + const header = document.getElementById("header") as HTMLElement; + const doc = Cast(this._parents.pop(), Doc) as Doc; // Parent document + // Case 1: Parent document is 'workspaces' + if (doc === Cast(this._library, Doc) as Doc) { + this._child = null; + this.switchCurrentView(this._library); + // Case 2: Parent document is the 'home' menu (root node) + } else if (doc === Cast(this._homeDoc, Doc) as Doc) { + this._homeMenu = true; + this._parents = []; + this._child = null; + this.switchCurrentView(this._homeDoc); + // Case 3: Parent document is any document + } else if (doc) { + this._child = doc; + this.switchCurrentView(doc); + this._homeMenu = false; + header.textContent = String(doc.title); } - DocServer.Mobile.dispatchOverlayTrigger({ - enableOverlay: true, - width: width, - height: height, - text: "Documents uploaded from mobile will show here", - }); + this._ink = false; // turns ink off } - renderDefaultContent = () => { - if (this.mainContainer) { - return <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} - docFilters={returnEmptyFilter} - ContainingCollectionView={undefined} - ContainingCollectionDoc={undefined} />; + /** + * Return 'Home", which implies returning to 'Home' menu buttons + */ + @action + returnHome = () => { + if (!this._homeMenu || this._sidebarActive) { + this._homeMenu = true; + this._parents = []; + this._child = null; + this.switchCurrentView(this._homeDoc); + } + if (this._sidebarActive) { + this.toggleSidebar(); } - return "hello"; } - onBack = (e: React.MouseEvent) => { - this.switchCurrentView((userDoc: Doc) => this.mainDoc); - Doc.SetSelectedTool(InkTool.None); // TODO: switch to previous tool + /** + * Return to primary Workspace in library (Workspaces Doc) + */ + @action + returnMain = () => { + this._parents = [this._homeDoc]; + this.switchCurrentView(this._library); + this._homeMenu = false; + this._child = null; + } + + /** + * Note: window.innerWidth and window.screen.width compute different values. + * window.screen.width is the display size, however window.innerWidth is the + * display resolution which computes differently. + */ + returnWidth = () => window.innerWidth; //The windows width + returnHeight = () => (window.innerHeight - 300); //Calculating the windows height (-300 to account for topbar) + whitebackground = () => "white"; + /** + * DocumentView for graphic display of all documents + */ + @computed get displayWorkspaces() { + return !this.mainContainer ? (null) : + <div style={{ position: "relative", top: '198px', height: `calc(100% - 350px)`, width: "100%", left: "0%" }}> + <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} + PanelWidth={this.returnWidth} + PanelHeight={this.returnHeight} + NativeHeight={returnZero} + NativeWidth={returnZero} + renderDepth={0} + focus={emptyFunction} + backgroundColor={this.whitebackground} + parentActive={returnTrue} + whenActiveChanged={emptyFunction} + bringToFront={emptyFunction} + docFilters={returnEmptyFilter} + ContainingCollectionView={undefined} + ContainingCollectionDoc={undefined} + /> + </div>; + } - DocServer.Mobile.dispatchOverlayTrigger({ - enableOverlay: false, - width: window.innerWidth, - height: window.innerHeight + /** + * 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) => { + runInAction(() => { + if (doc.type !== "collection" && this._sidebarActive) { + this._parents.push(this._activeDoc); + this.switchCurrentView(doc); + this._homeMenu = false; + this.toggleSidebar(); + } + else { + this._parents.push(this._activeDoc); + this.switchCurrentView(doc); + this._homeMenu = false; + this._child = doc; + } }); + } - // this.inkDoc = undefined; - this.drawingInk = false; + /** + * Called when an item in the library is clicked and should + * be opened (open icon on RHS of all menu items) + * @param doc doc to be opened + */ + @action + openFromSidebar = (doc: Doc) => { + this._parents.push(this._activeDoc); + this.switchCurrentView(doc); + this._homeMenu = false; + this._child = doc; + this.toggleSidebar(); } - shiftLeft = (e: React.MouseEvent) => { - DocServer.Mobile.dispatchOverlayPositionUpdate({ - dx: -10 - }); - e.preventDefault(); - e.stopPropagation(); + // Renders the graphical pathbar + renderPathbar = () => { + const docPath = [...this._parents, this._activeDoc]; + const items = docPath.map((doc: Doc, index: any) => + <div className="pathbarItem" key={index}> + {index === 0 ? (null) : <FontAwesomeIcon key="icon" className="pathIcon" icon="angle-right" size="lg" />} + <div className="pathbarText" + style={{ backgroundColor: this._homeMenu || doc === this._activeDoc ? "rgb(119,17,37)" : undefined }} + onClick={() => this.handlePathClick(doc, index)}>{doc.title} + </div> + </div>); + return (<div className="pathbar"> + <div className="scrollmenu"> + {items} + </div> + {!this._parents.length ? (null) : + <div className="back" > + <FontAwesomeIcon onClick={this.back} icon={"chevron-left"} color="white" size={"2x"} /> + </div>} + <div className="hidePath" /> + </div>); } - shiftRight = (e: React.MouseEvent) => { - DocServer.Mobile.dispatchOverlayPositionUpdate({ - dx: 10 - }); - e.preventDefault(); - e.stopPropagation(); + // Handles when user clicks on a document in the pathbar + @action + handlePathClick = (doc: Doc, index: number) => { + if (doc === this._library) { + this._child = null; + this.switchCurrentView(doc); + this._parents.length = index; + } else if (doc === this._homeDoc) { + this.returnHome(); + } else { + this._child = doc; + this.switchCurrentView(doc); + this._parents.length = index; + } } - panelHeight = () => window.innerHeight; - panelWidth = () => window.innerWidth; - renderInkingContent = () => { - console.log("rendering inking content"); - // TODO: support panning and zooming - // TODO: handle moving of ink strokes - if (this.mainContainer) { + // Renders the contents of the menu and sidebar + @computed get renderDefaultContent() { + if (this._homeMenu) { 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 className="navbar"> + <FontAwesomeIcon className="home" icon="home" onClick={this.returnHome} /> + <div className="header" id="header">{this._homeDoc.title}</div> + <div className="cover" id="cover" onClick={e => e.stopPropagation()}></div> + <div className="toggle-btn" id="menuButton" onClick={this.toggleSidebar}> + <span></span> + <span></span> + <span></span> </div> </div> - <CollectionView - Document={this.mainContainer} - DataDoc={undefined} - LibraryPath={emptyPath} - filterAddDocument={returnTrue} - 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} - docFilters={returnEmptyFilter} - ContainingCollectionView={undefined} - ContainingCollectionDoc={undefined} - rootSelected={returnTrue}> - </CollectionView> + {this.renderPathbar()} </div> ); } + // stores workspace documents as 'workspaces' variable + let workspaces = Cast(Doc.UserDoc().myWorkspaces, Doc) as Doc; + if (this._child) { + workspaces = this._child; + } + // returns a list of navbar buttons as 'buttons' + const buttons = DocListCast(workspaces.data).map((doc: Doc, index: any) => { + if (doc.type !== "ink") { + return ( + <div + className="item" + key={index}> + <div className="item-title" onClick={() => this.handleClick(doc)}> {doc.title} </div> + <div className="item-type" onClick={() => this.handleClick(doc)}>{doc.type}</div> + <FontAwesomeIcon onClick={() => this.handleClick(doc)} className="right" icon="angle-right" size="lg" style={{ display: `${doc.type === "collection" ? "block" : "none"}` }} /> + <FontAwesomeIcon className="open" onClick={() => this.openFromSidebar(doc)} icon="external-link-alt" size="lg" /> + </div> + ); + } + }); + + return ( + <div> + <div className="navbar"> + <FontAwesomeIcon className="home" icon="home" onClick={this.returnHome} /> + <div className="header" id="header">{this._sidebarActive ? "library" : this._activeDoc.title}</div> + <div className={`toggle-btn ${this._sidebarActive ? "active" : ""}`} onClick={this.toggleSidebar}> + <span></span> + <span></span> + <span></span> + </div> + <div className={`background ${this._sidebarActive ? "active" : ""}`} onClick={this.toggleSidebar}></div> + </div> + {this.renderPathbar()} + <div className={`sidebar ${this._sidebarActive ? "active" : ""}`}> + <div className="sidebarButtons"> + {this._child ? + <> + {buttons} + <div + className="item" key="home" + onClick={this.returnMain} + style={{ opacity: 0.7 }}> + <FontAwesomeIcon className="right" icon="angle-double-left" size="lg" /> + <div className="item-type">Return to workspaces</div> + </div> + </> : + <> + {buttons} + <div + className="item" + style={{ opacity: 0.7 }} + onClick={() => this.createNewWorkspace()}> + <FontAwesomeIcon className="right" icon="plus" size="lg" /> + <div className="item-type">Create New Workspace</div> + </div> + </> + } + </div> + </div> + <div className={`blanket ${this._sidebarActive ? "active" : ""}`} onClick={this.toggleSidebar}> + </div> + </div> + ); } - upload = async (e: React.MouseEvent) => { - if (this.mainContainer) { - const data = Cast(this.mainContainer.data, listSpec(Doc)); - if (data) { - const collectionDoc = await data[1]; // this should be the collection doc since the positions should be locked - const children = DocListCast(collectionDoc.data); - const uploadDoc = children.length === 1 ? children[0] : Docs.Create.StackingDocument(children, { - title: "Mobile Upload Collection", backgroundColor: "white", lockedPosition: true, _width: 300, _height: 300 - }); - if (uploadDoc) { - DocServer.Mobile.dispatchMobileDocumentUpload({ - docId: uploadDoc[Id], - }); - } - } - } - e.stopPropagation(); - e.preventDefault(); + /** + * Handles the 'Create New Workspace' button in the menu (taken from MainView.tsx) + */ + @action + createNewWorkspace = async (id?: string) => { + const workspaces = Cast(Doc.UserDoc().myWorkspaces, Doc) as Doc; + const workspaceCount = DocListCast(workspaces.data).length + 1; + const freeformOptions: DocumentOptions = { + x: 0, + y: 400, + title: "Collection " + workspaceCount, + }; + const freeformDoc = CurrentUserUtils.GuestTarget || Docs.Create.FreeformDocument([], freeformOptions); + const workspaceDoc = Docs.Create.StandardCollectionDockingDocument([{ doc: freeformDoc, initialWidth: 600, path: [Doc.UserDoc().myCatalog as Doc] }], { title: `Workspace ${workspaceCount}` }, id, "row"); + + const toggleTheme = ScriptField.MakeScript(`self.darkScheme = !self.darkScheme`); + const toggleComic = ScriptField.MakeScript(`toggleComicMode()`); + const cloneWorkspace = ScriptField.MakeScript(`cloneWorkspace()`); + workspaceDoc.contextMenuScripts = new List<ScriptField>([toggleTheme!, toggleComic!, cloneWorkspace!]); + workspaceDoc.contextMenuLabels = new List<string>(["Toggle Theme Colors", "Toggle Comic Mode", "New Workspace Layout"]); + + Doc.AddDocToList(workspaces, "data", workspaceDoc); } - addWebToCollection = async () => { - let url = "https://en.wikipedia.org/wiki/Hedgehog"; - if (this.mainContainer) { - const data = Cast(this.mainContainer.data, listSpec(Doc)); - if (data) { - const webDoc = await data[0]; - const urlField: FieldResult<WebField> = Cast(webDoc.data, WebField); - url = urlField ? urlField.url.toString() : "https://en.wikipedia.org/wiki/Hedgehog"; + // Button for switching between pen and ink mode + @action + onSwitchInking = () => { + const button = document.getElementById("inkButton") as HTMLElement; + button.style.backgroundColor = this._ink ? "white" : "black"; + button.style.color = this._ink ? "black" : "white"; - } - } - Docs.Create.WebDocument(url, { _width: 300, _height: 300, title: "Mobile Upload Web Doc" }); - } - - clearUpload = async () => { - if (this.mainContainer) { - const data = Cast(this.mainContainer.data, listSpec(Doc)); - if (data) { - const collectionDoc = await data[1]; - const children = DocListCast(collectionDoc.data); - children.forEach(doc => { - }); - // collectionDoc[data] = new List<Doc>(); - } + if (!this._ink) { + Doc.SetSelectedTool(InkTool.Pen); + this._ink = true; + } else { + Doc.SetSelectedTool(InkTool.None); + this._ink = false; } } - renderUploadContent() { - if (this.mainContainer) { + // The static ink menu that appears at the top + @computed get inkMenu() { + return this._activeDoc._viewType !== CollectionViewType.Docking || !this._ink ? (null) : + <div className="colorSelector"> + <InkOptionsMenu /> + </div>; + } + + // DocButton that uses UndoManager and handles the opacity change if CanUndo is true + @computed get undo() { + if (this.mainContainer && this._activeDoc.type === "collection" && this._activeDoc !== this._homeDoc && + this._activeDoc !== Doc.UserDoc().rightSidebarCollection && this._activeDoc.title !== "WORKSPACES") { 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} - docFilters={returnEmptyFilter} - ContainingCollectionView={undefined} - ContainingCollectionDoc={undefined} /> + <div className="docButton" + style={{ backgroundColor: "black", color: "white", fontSize: "60", opacity: UndoManager.CanUndo() ? "1" : "0.4", }} + id="undoButton" + title="undo" + onClick={(e: React.MouseEvent) => { + UndoManager.Undo(); + e.stopPropagation(); + }}> + <FontAwesomeIcon className="documentdecorations-icon" size="sm" icon="undo-alt" /> + </div>); + } else return (null); + } + + // DocButton that uses UndoManager and handles the opacity change if CanRedo is true + @computed get redo() { + if (this.mainContainer && this._activeDoc.type === "collection" && this._activeDoc !== this._homeDoc && + this._activeDoc !== Doc.UserDoc().rightSidebarCollection && this._activeDoc.title !== "WORKSPACES") { + return ( + <div className="docButton" + style={{ backgroundColor: "black", color: "white", fontSize: "60", opacity: UndoManager.CanRedo() ? "1" : "0.4", }} + id="undoButton" + title="redo" + onClick={(e: React.MouseEvent) => { + UndoManager.Redo(); + e.stopPropagation(); + }}> + <FontAwesomeIcon className="documentdecorations-icon" size="sm" icon="redo-alt" /> + </div>); + } else return (null); + } + + // DocButton for switching into ink mode + @computed get drawInk() { + return !this.mainContainer || this._activeDoc._viewType !== CollectionViewType.Docking ? (null) : + <div className="docButton" + id="inkButton" + title={Doc.isDocPinned(this._activeDoc) ? "Pen on" : "Pen off"} + onClick={this.onSwitchInking}> + <FontAwesomeIcon className="documentdecorations-icon" size="sm" icon="pen-nib" /> + </div>; + } + + // DocButton: Button that appears on the bottom of the screen to initiate image upload + @computed get uploadImageButton() { + if (this._activeDoc.type === DocumentType.COL && this._activeDoc !== this._homeDoc && this._activeDoc._viewType !== CollectionViewType.Docking && this._activeDoc.title !== "WORKSPACES") { + return <div className="docButton" + id="imageButton" + title={Doc.isDocPinned(this._activeDoc) ? "Pen on" : "Pen off"} + onClick={this.toggleUpload}> + <FontAwesomeIcon className="documentdecorations-icon" size="sm" icon="upload" /> + </div>; + } else return (null); + } + + // DocButton to download images on the mobile + @computed get downloadDocument() { + if (this._activeDoc.type === "image" || this._activeDoc.type === "pdf" || this._activeDoc.type === "video") { + return <div className="docButton" + title={"Download Image"} + style={{ backgroundColor: "white", color: "black" }} + onClick={e => window.open(this._activeDoc["data-path"]?.toString())}> {/* daa-path holds the url */} + <FontAwesomeIcon className="documentdecorations-icon" size="sm" icon="download" /> + </div>; + } else return (null); + } + + // DocButton for pinning images to presentation + @computed get pinToPresentation() { + // Only making button available if it is an image + if (!(this._activeDoc.type === "collection" || this._activeDoc.type === "presentation")) { + const isPinned = this._activeDoc && Doc.isDocPinned(this._activeDoc); + return <div className="docButton" + title={Doc.isDocPinned(this._activeDoc) ? "Unpin from presentation" : "Pin to presentation"} + style={{ backgroundColor: isPinned ? "black" : "white", color: isPinned ? "white" : "black" }} + onClick={e => DockedFrameRenderer.PinDoc(this._activeDoc, isPinned)}> + <FontAwesomeIcon className="documentdecorations-icon" size="sm" icon="map-pin" /> + </div>; + } else return (null); + } + + // Buttons for switching the menu between large and small icons + @computed get switchMenuView() { + return this._activeDoc.title !== this._homeDoc.title ? (null) : + <div className="homeSwitch"> + <div className={`list ${!this._menuListView ? "active" : ""}`} onClick={this.changeToIconView}> + <FontAwesomeIcon size="sm" icon="th-large" /> </div> - ); + <div className={`list ${this._menuListView ? "active" : ""}`} onClick={this.changeToListView}> + <FontAwesomeIcon size="sm" icon="bars" /> + </div> + </div>; + } + + // Logic for switching the menu into the icons + @action + changeToIconView = () => { + if (this._homeDoc._viewType = "stacking") { + this._menuListView = false; + this._homeDoc._viewType = "masonry"; + this._homeDoc.columnWidth = 300; + this._homeDoc._columnWidth = 300; + const menuButtons = DocListCast(this._homeDoc.data); + menuButtons.map(doc => { + const buttonData = DocListCast(doc.data); + buttonData[1]._nativeWidth = 0.1; + buttonData[1]._width = 0.1; + buttonData[1]._dimMagnitude = 0; + buttonData[1]._opacity = 0; + doc._nativeWidth = 400; + }); } } + // Logic for switching the menu into the stacking view + @action + changeToListView = () => { + if (this._homeDoc._viewType = "masonry") { + this._homeDoc._viewType = "stacking"; + this._menuListView = true; + const menuButtons = DocListCast(this._homeDoc.data); + menuButtons.map(doc => { + const buttonData = DocListCast(doc.data); + buttonData[1]._nativeWidth = 450; + buttonData[1]._dimMagnitude = 2; + buttonData[1]._opacity = 1; + doc._nativeWidth = 900; + }); + } + } + + // For setting up the presentation document for the home menu + @action + setupDefaultPresentation = () => { + const presentation = Cast(Doc.UserDoc().activePresentation, Doc) as Doc; + + if (presentation) { + this.switchCurrentView(presentation); + this._homeMenu = false; + } + } + + // For toggling image upload pop up + @action + toggleUpload = () => this._imageUploadActive = !this._imageUploadActive + + // For toggling audio record and dictate pop up + @action + toggleAudio = () => this._audioUploadActive = !this._audioUploadActive + + // Button for toggling the upload pop up in a collection + @action + toggleUploadInCollection = () => { + const button = document.getElementById("imageButton") as HTMLElement; + button.style.backgroundColor = this._imageUploadActive ? "white" : "black"; + button.style.color = this._imageUploadActive ? "black" : "white"; + + this._imageUploadActive = !this._imageUploadActive; + } + + // For closing the image upload pop up + @action + closeUpload = () => { + this._imageUploadActive = false; + } + + // Returns the image upload pop up + @computed get uploadImage() { + const doc = !this._homeMenu ? this._activeDoc : Cast(Doc.UserDoc().rightSidebarCollection, Doc) as Doc; + return <Uploader Document={doc} />; + } + + // Radial menu can only be used if it is a colleciton and it is not a homeDoc + // (and cannot be used on Workspace to avoid pin to presentation opening on right) + @computed get displayRadialMenu() { + return this._activeDoc.type === "collection" && this._activeDoc !== this._homeDoc && + this._activeDoc._viewType !== CollectionViewType.Docking ? <RadialMenu /> : (null); + } + onDragOver = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); } + /** + * MENU BUTTON + * Switch view from mobile menu to access the mobile uploads + * Global function name: openMobileUploads() + */ + @action + switchToMobileUploads = () => { + const mobileUpload = Cast(Doc.UserDoc().rightSidebarCollection, Doc) as Doc; + this.switchCurrentView(mobileUpload); + this._homeMenu = false; + } + render() { - // const content = this.currentView === "main" ? this.mainContent : - // this.currentView === "ink" ? this.inkContent : - // this.currentView === "upload" ? this.uploadContent : <></>; return ( <div className="mobileInterface-container" onDragOver={this.onDragOver}> - {/* <DocumentDecorations /> - <GestureOverlay> - {this.renderView ? this.renderView() : this.renderDefaultContent()} - </GestureOverlay> */} - - {/* <DictationOverlay /> - <SharingManager /> - <GoogleAuthenticationManager /> */} - <DocumentDecorations /> + <SettingsManager /> + <div className={`image-upload ${this._imageUploadActive ? "active" : ""}`}> + {this.uploadImage} + </div> + <div className={`audio-upload ${this._audioUploadActive ? "active" : ""}`}> + <AudioUpload /> + </div> + {this.switchMenuView} + {this.inkMenu} <GestureOverlay> - {this.renderView ? this.renderView() : this.renderDefaultContent()} + <div style={{ display: "none" }}><RichTextMenu key="rich" /></div> + <div className="docButtonContainer"> + {this.pinToPresentation} + {this.downloadDocument} + {this.undo} + {this.redo} + {this.drawInk} + {this.uploadImageButton} + </div> + {this.displayWorkspaces} + {this.renderDefaultContent} </GestureOverlay> - <PreviewCursor /> - {/* <ContextMenu /> */} - <RadialMenu /> - <RichTextMenu /> - {/* <PDFMenu /> - <MarqueeOptionsMenu /> - <OverlayView /> */} + {this.displayRadialMenu} </div> ); } } -Scripting.addGlobal(function switchMobileView(doc: (userDoc: Doc) => Doc, renderView?: () => JSX.Element, onSwitch?: () => void) { return MobileInterface.Instance.switchCurrentView(doc, renderView, onSwitch); }); -Scripting.addGlobal(function onSwitchMobileInking() { return MobileInterface.Instance.onSwitchInking(); }); -Scripting.addGlobal(function renderMobileInking() { return MobileInterface.Instance.renderInkingContent(); }); -Scripting.addGlobal(function onSwitchMobileUpload() { return MobileInterface.Instance.onSwitchUpload(); }); -Scripting.addGlobal(function renderMobileUpload() { return MobileInterface.Instance.renderUploadContent(); }); -Scripting.addGlobal(function addWebToMobileUpload() { return MobileInterface.Instance.addWebToCollection(); }); +//Global functions for mobile menu +Scripting.addGlobal(function switchToMobileLibrary() { return MobileInterface.Instance.switchToLibrary(); }, + "opens the library to navigate through workspaces on Dash Mobile"); +Scripting.addGlobal(function openMobileUploads() { return MobileInterface.Instance.toggleUpload(); }, + "opens the upload files menu for Dash Mobile"); +Scripting.addGlobal(function switchToMobileUploadCollection() { return MobileInterface.Instance.switchToMobileUploads(); }, + "opens the mobile uploads collection on Dash Mobile"); +Scripting.addGlobal(function openMobileAudio() { return MobileInterface.Instance.toggleAudio(); }, + "opens the record and dictate menu on Dash Mobile"); +Scripting.addGlobal(function switchToMobilePresentation() { return MobileInterface.Instance.setupDefaultPresentation(); }, + "opens the presentation on Dash Mobile"); +Scripting.addGlobal(function openMobileSettings() { return SettingsManager.Instance.open(); }, + "opens settings on Dash Mobile"); + +// Other global functions for mobile +Scripting.addGlobal(function switchMobileView(doc: Doc, renderView?: () => JSX.Element, onSwitch?: () => void) { return MobileInterface.Instance.switchCurrentView(doc, renderView, onSwitch); }, + "changes the active document displayed on the Dash Mobile", "(doc: any)"); diff --git a/src/mobile/MobileMain.tsx b/src/mobile/MobileMain.tsx new file mode 100644 index 000000000..3d4680d58 --- /dev/null +++ b/src/mobile/MobileMain.tsx @@ -0,0 +1,25 @@ +import { MobileInterface } from "./MobileInterface"; +import { Docs } from "../client/documents/Documents"; +import { CurrentUserUtils } from "../client/util/CurrentUserUtils"; +import * as ReactDOM from 'react-dom'; +import * as React from 'react'; +import { DocServer } from "../client/DocServer"; +import { AssignAllExtensions } from "../extensions/General/Extensions"; + +AssignAllExtensions(); + +(async () => { + const info = await CurrentUserUtils.loadCurrentUser(); + DocServer.init(window.location.protocol, window.location.hostname, 4321, info.email + " (mobile)"); + await Docs.Prototypes.initialize(); + if (info.id !== "__guest__") { + // a guest will not have an id registered + await CurrentUserUtils.loadUserDocument(info); + } + document.getElementById('root')!.addEventListener('wheel', event => { + if (event.ctrlKey) { + event.preventDefault(); + } + }, true); + ReactDOM.render(<MobileInterface />, document.getElementById('root')); +})();
\ No newline at end of file diff --git a/src/mobile/MobileMenu.scss b/src/mobile/MobileMenu.scss new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/src/mobile/MobileMenu.scss diff --git a/src/pen-gestures/ndollar.ts b/src/pen-gestures/ndollar.ts index 9d42035d1..ecd8df3e7 100644 --- a/src/pen-gestures/ndollar.ts +++ b/src/pen-gestures/ndollar.ts @@ -552,7 +552,7 @@ function Distance(p1: any, p2: any) // distance between two points } function CalcStartUnitVector(points: any, index: any) // start angle from points[0] to points[index] normalized as a unit vector { - const v = new Point(points[index].X - points[0].X, points[index].Y - points[0].Y); + const v = new Point(points[index]?.X - points[0]?.X, points[index]?.Y - points[0]?.Y); const len = Math.sqrt(v.X * v.X + v.Y * v.Y); return new Point(v.X / len, v.Y / len); } diff --git a/src/scraping/buxton/scraper.py b/src/scraping/buxton/scraper.py index ed122e544..312915e2d 100644 --- a/src/scraping/buxton/scraper.py +++ b/src/scraping/buxton/scraper.py @@ -91,14 +91,13 @@ def write_collection(parse_results, display_fields, storage_key, viewType): "zIndex": 2, "libraryBrush": False, "_viewType": viewType, - "_LODdisable": True }, "__type": "Doc" } fields["proto"] = protofy(common_proto_id) fields[storage_key] = listify(proxify_guids(view_guids)) - fields["schemaColumns"] = listify(display_fields) + fields["_columnHeaders"] = listify(display_fields) fields["author"] = "Bill Buxton" fields["creationDate"] = { "date": datetime.datetime.utcnow().microsecond, diff --git a/src/server/ApiManagers/PDFManager.ts b/src/server/ApiManagers/PDFManager.ts index d2a9e9cce..2b4212588 100644 --- a/src/server/ApiManagers/PDFManager.ts +++ b/src/server/ApiManagers/PDFManager.ts @@ -2,6 +2,7 @@ import ApiManager, { Registration } from "./ApiManager"; import { Method } from "../RouteManager"; import RouteSubscriber from "../RouteSubscriber"; import { existsSync, createReadStream, createWriteStream } from "fs"; +const pdfjs = require('pdfjs-dist/es5/build/pdf.js'); import * as Pdfjs from 'pdfjs-dist'; import { createCanvas } from "canvas"; const imageSize = require("probe-image-size"); @@ -51,11 +52,13 @@ async function getOrCreateThumbnail(coreFilename: string, pageNum: number, res: } async function CreateThumbnail(coreFilename: string, pageNum: number, res: express.Response, subtree?: string) { - const sourcePath = resolve(pathToDirectory(Directory.pdfs), `${subtree ?? ""}${coreFilename}.pdf`); + const part1 = subtree ?? ""; + const filename = `${part1}${coreFilename}.pdf`; + const sourcePath = resolve(pathToDirectory(Directory.pdfs), filename); const documentProxy = await Pdfjs.getDocument(sourcePath).promise; const factory = new NodeCanvasFactory(); const page = await documentProxy.getPage(pageNum); - const viewport = page.getViewport(1 as any); + const viewport = page.getViewport({ scale: 1, rotation: 0, dontFlip: false }); const { canvas, context } = factory.create(viewport.width, viewport.height); const renderContext = { canvasContext: context, @@ -111,4 +114,4 @@ class NodeCanvasFactory { canvasAndContext.canvas = null; canvasAndContext.context = null; } -}
\ No newline at end of file +} diff --git a/src/server/index.ts b/src/server/index.ts index 590affd06..083173bb5 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -104,6 +104,7 @@ function routeSetter({ isRelease, addSupervisedRoute, logRegistrationOutcome }: const serve: PublicHandler = ({ req, res }) => { const detector = new mobileDetect(req.headers['user-agent'] || ""); const filename = detector.mobile() !== null ? 'mobile/image.html' : 'index.html'; + console.log(detector.is("iPhone")); res.sendFile(path.join(__dirname, '../../deploy/' + filename)); }; |