diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/client/documents/Documents.ts | 2 | ||||
-rw-r--r-- | src/client/views/EditableView.tsx | 29 | ||||
-rw-r--r-- | src/client/views/collections/CollectionSchemaCells.tsx | 502 | ||||
-rw-r--r-- | src/client/views/collections/CollectionSchemaHeaders.tsx | 62 | ||||
-rw-r--r-- | src/client/views/collections/CollectionSchemaMovableTableHOC.tsx | 2 | ||||
-rw-r--r-- | src/client/views/collections/CollectionSchemaView.scss | 77 | ||||
-rw-r--r-- | src/client/views/collections/CollectionSchemaView.tsx | 1029 | ||||
-rw-r--r-- | src/client/views/collections/SchemaTable.tsx | 609 | ||||
-rw-r--r-- | src/client/views/linking/LinkMenu.tsx | 2 |
9 files changed, 1724 insertions, 590 deletions
diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index e8801df90..5cbbe526e 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -398,7 +398,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; diff --git a/src/client/views/EditableView.tsx b/src/client/views/EditableView.tsx index bab3a1634..a4f2f17fc 100644 --- a/src/client/views/EditableView.tsx +++ b/src/client/views/EditableView.tsx @@ -182,11 +182,39 @@ export class EditableView extends React.Component<EditableProps> { } render() { if (this._editing && this.props.GetValue() !== undefined) { +<<<<<<< HEAD + 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(); +>>>>>>> 790cc785a5cad47f0dd274c7f4773eff7d7d9c2e } else { this.props.autosuggestProps?.resetValue(); return (this.props.contents instanceof ObjectField ? (null) : @@ -194,7 +222,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/collections/CollectionSchemaCells.tsx b/src/client/views/collections/CollectionSchemaCells.tsx index 2b8110e27..593962e73 100644 --- a/src/client/views/collections/CollectionSchemaCells.tsx +++ b/src/client/views/collections/CollectionSchemaCells.tsx @@ -1,21 +1,21 @@ 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 { CollectionView, Flyout } from "./CollectionView"; import { NumCast, StrCast, BoolCast, FieldValue, Cast } from "../../../fields/Types"; import { Docs } from "../../documents/Documents"; import { library } from '@fortawesome/fontawesome-svg-core'; @@ -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 { LinkBox } from "../nodes/LinkBox"; +import { OverlayView } from "../OverlayView"; +import { DocumentIconContainer } from "../nodes/DocumentIcon"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { ContentFittingDocumentView } from "../nodes/ContentFittingDocumentView"; +import ReactDOM from "react-dom"; +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,15 @@ 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}--`; + } + let className = "collectionSchemaView-cellWrapper"; if (this._isEditing) className += " editing"; @@ -220,40 +240,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?.substring(0, cfinalScript.length - 2)}` : + 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 +305,8 @@ export class CollectionSchemaCell extends React.Component<CellProps> { } }} /> + + </div > {/* {fieldIsDoc ? docExpander : null} */} </div> @@ -300,12 +342,444 @@ export class CollectionSchemaStringCell extends CollectionSchemaCell { @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.prop.Document[this.prop.fieldKey] = results.result; + this.prop.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.prop.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..80c265ba6 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 } 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); export interface HeaderProps { keyValue: SchemaHeaderField; @@ -33,7 +33,8 @@ 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" : "align-justify"; return ( <div className="collectionSchemaView-header" style={{ background: this.props.keyValue.color }}> <CollectionSchemaColumnMenu @@ -72,6 +73,16 @@ export class CollectionSchemaAddColumnHeader extends React.Component<AddColumnHe } } + + + + + + + + + + export interface ColumnMenuProps { columnField: SchemaHeaderField; // keyValue: string; @@ -160,10 +171,18 @@ 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> </div > ); @@ -258,7 +277,7 @@ export class CollectionSchemaColumnMenu extends React.Component<ColumnMenuProps> } -interface KeysDropdownProps { +export interface KeysDropdownProps { keyValue: string; possibleKeys: string[]; existingKeys: string[]; @@ -266,9 +285,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 +351,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, 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, overflowX: "hidden" + }} onClick={() => { this.onSelect(this._searchTerm); this.setSearchTerm(""); }}> Create "{this._searchTerm}" key</div>); } @@ -351,10 +380,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 }}> + <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, 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..2926a8f6f 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: 10000; + overflow-y: visible; + &.-header { font-size: 12px; height: 30px; box-shadow: none; + z-index: 10000; + overflow-y: visible; } .rt-resizable-header-content { @@ -175,11 +180,18 @@ .collectionSchemaView-header { height: 100%; color: gray; + z-index: 10000; + overflow-y: visible; + display: flex; + justify-content: space-between; + flex-wrap: wrap; .collectionSchema-header-menu { height: 100%; + z-index: 10000; .collectionSchema-header-toggler { + z-index: 10000; width: 100%; height: 100%; padding: 4px; @@ -253,13 +265,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 +288,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 +430,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 +490,7 @@ button.add-column { top: 0; right: 0; background-color: lightgray; + } .doc-drag-over { @@ -429,6 +498,10 @@ button.add-column { } .collectionSchemaView-toolbar { + z-index: 1000; +} + +.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..bfd5fa96f 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 { civicinfo } from "googleapis/build/src/apis/civicinfo"; library.add(faCog, faPlus, faSortUp, faSortDown); library.add(faTable); @@ -40,6 +36,8 @@ export enum ColumnType { String, Boolean, Doc, + Image, + List } // this map should be used for keys that should have a const type of value const columnTypes: Map<string, ColumnType> = new Map([ @@ -62,6 +60,387 @@ 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); + } + + @computed get columns() { + return Cast(this.props.Document.schemaColumns, listSpec(SchemaHeaderField), []); + } + set columns(columns: SchemaHeaderField[]) { + this.props.Document.schemaColumns = 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; + } + + @action + 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 allColumnTypes = <div className="columnMenu-types"> + {anyType} + {numType} + {textType} + {boolType} + {listType} + {docType} + {imageType} + </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 : 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} + />; + } + + @action + renderContent = (col: any) => { + return ( + <div className="collectionSchema-header-menuOptions"> + <div className="collectionSchema-headerMenu-group"> + <label>Key:</label> + {this.renderKeysDropDown(col)} + </div> + {false ? <></> : + <> + {this.renderTypes(col)} + {this.renderSorting(col)} + {this.renderColors(col)} + <div className="collectionSchema-headerMenu-group"> + <button onClick={() => { this.deleteColumn(col.heading); }} + >Delete Column</button> + </div> + </> + } + </div> + ); + } + + @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; + } + + @action renderMenu() { + const scale = this.props.ScreenToLocalTransform().Scale; + return ( + <div className="collectionSchema-header-menu" ref={this.setNode} + onWheel={e => this.props.active(true) && e.stopPropagation()} + onPointerDown={e => this.onHeaderClick(e)} + style={{ + position: "absolute", background: "white", + transform: `translate(${this.menuCoordinates[0] * scale}px, ${this.menuCoordinates[1] / 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}> + <div className="collectionSchema-header-menuOptions"> + <div className="collectionSchema-headerMenu-group"> + <label>Key:</label> + {this.renderKeysDropDown(this._col)} + </div> + {false ? <></> : + <> + {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> + + </div>} + </Measure> + </div> + ); + } + private createTarget = (ele: HTMLDivElement) => { this._previewCont = ele; super.CreateDropTarget(ele); @@ -105,14 +484,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 +551,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 +569,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> - </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 id="preview-schema-checkbox-div"> + <input type="checkbox" + key={"Show Preview"} checked={this.previewWidth() !== 0} + onChange={this.toggleExpander} />Show Preview</div> </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 +614,58 @@ 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>([]); - } 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" }); - } - } - - 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; - } - } + render() { + const scale = this.props.ScreenToLocalTransform().Scale; + const menu = <div className="collectionSchema-header-menu" ref={this.setNode} + onWheel={e => this.props.active(true) && e.stopPropagation()} + onPointerDown={e => this.onHeaderClick(e)} + style={{ + position: "absolute", background: "white", + transform: `translate(${this.menuCoordinates[0] * scale}px, ${this.menuCoordinates[1] / 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}> + <div className="collectionSchema-header-menuOptions"> + <div className="collectionSchema-headerMenu-group"> + <label>Key:</label> + {this.renderKeysDropDown(this._col)} + </div> + {false ? <></> : + <> + {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> + </> } - } - - return node; - } - return ts.visitNode(root, visit); - }; - }; - - // const getVars = () => { - // return { capturedVariables: captures }; - // }; + </div> - 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; - } - return false; - } + </div>} + </Measure> + </div>; - 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> + 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/SchemaTable.tsx b/src/client/views/collections/SchemaTable.tsx new file mode 100644 index 000000000..176091661 --- /dev/null +++ b/src/client/views/collections/SchemaTable.tsx @@ -0,0 +1,609 @@ +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 } 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 +} + +// 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" : "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: 10000 }}> + {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} />; + 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.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).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; + } + 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/linking/LinkMenu.tsx b/src/client/views/linking/LinkMenu.tsx index 0fcc0f0b9..de1d60a09 100644 --- a/src/client/views/linking/LinkMenu.tsx +++ b/src/client/views/linking/LinkMenu.tsx @@ -28,7 +28,7 @@ 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)) { + if (this._linkMenuRef?.contains(e.target as any)) { DocumentLinksButton.EditLink = undefined; } } |