import ReactTextareaAutocomplete from "@webscopeio/react-textarea-autocomplete"; import "@webscopeio/react-textarea-autocomplete/style.css"; import { action, computed, observable, runInAction, trace } from "mobx"; import { observer } from "mobx-react"; import * as React from "react"; import { Doc } from "../../../fields/Doc"; import { documentSchema } from "../../../fields/documentSchemas"; import { List } from "../../../fields/List"; import { createSchema, listSpec, makeInterface } from "../../../fields/Schema"; import { ScriptField } from "../../../fields/ScriptField"; import { Cast, NumCast, ScriptCast, StrCast } from "../../../fields/Types"; import { returnEmptyString } from "../../../Utils"; import { DragManager } from "../../util/DragManager"; import { InteractionUtils } from "../../util/InteractionUtils"; import { CompileScript, Scripting, ScriptParam } from "../../util/Scripting"; import { ScriptManager } from "../../util/ScriptManager"; import { ContextMenu } from "../ContextMenu"; import { ViewBoxAnnotatableComponent } from "../DocComponent"; import { EditableView } from "../EditableView"; import { FieldView, FieldViewProps } from "../nodes/FieldView"; import { OverlayView } from "../OverlayView"; import { DocumentIconContainer } from "./DocumentIcon"; import "./ScriptingBox.scss"; const _global = (window /* browser */ || global /* node */) as any; const ScriptingSchema = createSchema({}); type ScriptingDocument = makeInterface<[typeof ScriptingSchema, typeof documentSchema]>; const ScriptingDocument = makeInterface(ScriptingSchema, documentSchema); @observer export class ScriptingBox extends ViewBoxAnnotatableComponent(ScriptingDocument) { private dropDisposer?: DragManager.DragDropDisposer; protected multiTouchDisposer?: InteractionUtils.MultiTouchEventDisposer | undefined; public static LayoutString(fieldStr: string) { return FieldView.LayoutString(ScriptingBox, fieldStr); } private _overlayDisposer?: () => void; @observable private _errorMessage: string = ""; @observable private _applied: boolean = false; @observable private _function: boolean = false; @observable private _hovered: boolean = false; @observable private _spaced: boolean = false; @observable private _scriptKeys: any = Scripting.getGlobals(); @observable private _scriptGlobals: any = Scripting.getGlobalObj(); @observable private _currWord: string = ""; @observable private _suggestions: string[] = []; @observable private _suggestionBoxX: number = 0; @observable private _suggestionBoxY: number = 0; @observable private _lastChar: string = ""; @observable private _suggestionRef: any = React.createRef(); @observable private _scriptTextRef: any = React.createRef(); @observable private _selection: any = 0; @observable private _selectionEnd: any = 0; @observable private _paramSuggestion: boolean = false; @observable private _scriptSuggestedParams: any = ""; @observable private _scriptParamsText: any = ""; // vars included in fields that store parameters types and names and the script itself @computed({ keepAlive: true }) get paramsNames() { return this.compileParams.map(p => p.split(":")[0].trim()); } @computed({ keepAlive: true }) get paramsTypes() { return this.compileParams.map(p => p.split(":")[1].trim()); } @computed({ keepAlive: true }) get rawScript() { return StrCast(this.dataDoc[this.props.fieldKey + "-rawScript"], ""); } @computed({ keepAlive: true }) get functionName() { return StrCast(this.dataDoc[this.props.fieldKey + "-functionName"], ""); } @computed({ keepAlive: true }) get functionDescription() { return StrCast(this.dataDoc[this.props.fieldKey + "-functionDescription"], ""); } @computed({ keepAlive: true }) get compileParams() { return Cast(this.dataDoc[this.props.fieldKey + "-params"], listSpec("string"), []); } set rawScript(value) { this.dataDoc[this.props.fieldKey + "-rawScript"] = value; } set functionName(value) { this.dataDoc[this.props.fieldKey + "-functionName"] = value; } set functionDescription(value) { this.dataDoc[this.props.fieldKey + "-functionDescription"] = value; } set compileParams(value) { this.dataDoc[this.props.fieldKey + "-params"] = new List(value); } // WORK ON THIS // in: global, description, params @computed get _descriptions() { const descrip: string[] = []; this._scriptKeys.forEach((element: any) => { const result = this._scriptGlobals[element]; descrip.push(this.getValue(result, true)); }); return descrip; } @computed get _scriptParams() { const params: string[] = []; this._scriptKeys.forEach((element: any) => { const result = this._scriptGlobals[element]; params.push(this.getValue(result, false)); }); return params; } getValue(result: any, descrip: boolean) { let value = ""; if (typeof result === "object") { let text = ""; if (descrip) { text = result[1]; } else { text = result[2]; } if (text !== undefined) { value = text; } else { value = ""; } } else { value = ""; } return value; } @action componentDidMount() { this.rawScript = ScriptCast(this.dataDoc[this.props.fieldKey])?.script?.originalScript ?? this.rawScript; const observer = new _global.ResizeObserver(action((entries: any) => { for (const { } of entries) { const getCaretCoordinates = require('textarea-caret'); const caret = getCaretCoordinates(this._selection, this._selectionEnd); this.resetSuggestionPos(caret); } })); observer.observe(document.getElementsByClassName("scriptingBox")[0]); } @action resetSuggestionPos(caret: any) { console.log('(top, left, height) = (%s, %s, %s)', caret.top, caret.left, caret.height); let top = caret.top; let left = caret.left; const x = this.dataDoc.x; const suggestionWidth = this._suggestionRef.current.offsetWidth; const scriptWidth = this._scriptTextRef.current.offsetWidth; if ((left + suggestionWidth) > (x + scriptWidth)) { const diff = (left + suggestionWidth) - (x + scriptWidth); left = left - diff; } runInAction(() => { this._suggestionBoxX = left; this._suggestionBoxY = top; }); } componentWillUnmount() { this._overlayDisposer?.(); } protected createDashEventsTarget = (ele: HTMLDivElement, dropFunc: (e: Event, de: DragManager.DropEvent) => void) => { //used for stacking and masonry view if (ele) { this.dropDisposer?.(); this.dropDisposer = DragManager.MakeDropTarget(ele, dropFunc, this.layoutDoc); } } // only included in buttons, transforms scripting UI to a button @action onFinish = () => { this.rootDoc.layoutKey = "layout"; this.rootDoc._height = 50; this.rootDoc._width = 100; this.dataDoc.documentText = this.rawScript; } // displays error message @action onError = (error: any) => { this._errorMessage = error?.map((entry: any) => entry.messageText).join(" ") || ""; } // checks if the script compiles using CompileScript method and inputting params @action onCompile = () => { const params: ScriptParam = {}; this.compileParams.forEach(p => params[p.split(":")[0].trim()] = p.split(":")[1].trim()); const result = CompileScript(this.rawScript, { editable: true, transformer: DocumentIconContainer.getTransformer(), params, typecheck: false }); this.dataDoc.documentText = this.rawScript; this.dataDoc.data = result.compiled ? new ScriptField(result) : undefined; this.onError(result.compiled ? undefined : result.errors); if (result.compiled) { return true; } else { return false; } } // checks if the script compiles and then runs the script @action onRun = () => { if (this.onCompile()) { const bindings: { [name: string]: any } = {}; this.paramsNames.forEach(key => bindings[key] = this.dataDoc[key]); // binds vars so user doesnt have to refer to everything as self. ScriptCast(this.dataDoc.data, null)?.script.run({ self: this.rootDoc, this: this.layoutDoc, ...bindings }, this.onError); } } // checks if the script compiles and switches to applied UI @action onApply = () => { if (this.onCompile()) { this._applied = true; } } @action onEdit = () => { this._errorMessage = ""; this._applied = false; this._function = false; } @action onSave = () => { if (this.onCompile()) { this._function = true; } else { this._errorMessage = "Can not save script, does not compile"; } } @action onCreate = () => { this._errorMessage = ""; if (this.functionName.length === 0) { this._errorMessage = "Must enter a function name"; return false; } if (this.functionName.indexOf(" ") > 0) { this._errorMessage = "Name can not include spaces"; return false; } this.dataDoc.funcName = this.functionName; this.dataDoc.descripition = this.functionDescription; ScriptManager.Instance.deleteScript(this.dataDoc); ScriptManager.Instance.addScript(this.dataDoc); console.log("created"); } // overlays document numbers (ex. d32) over all documents when clicked on onFocus = () => { this._overlayDisposer?.(); this._overlayDisposer = OverlayView.Instance.addElement(, { x: 0, y: 0 }); } // sets field of the corresponding field key (param name) to be dropped document @action onDrop = (e: Event, de: DragManager.DropEvent, fieldKey: string) => { this.dataDoc[fieldKey] = de.complete.docDragData?.droppedDocuments[0]; e.stopPropagation(); } // deletes a param from all areas in which it is stored @action onDelete = (num: number) => { this.dataDoc[this.paramsNames[num]] = undefined; this.compileParams.splice(num, 1); return true; } // sets field of the param name to the selected value in drop down box @action viewChanged = (e: React.ChangeEvent, name: string) => { //@ts-ignore this.dataDoc[name] = e.target.selectedOptions[0].value; } // creates a copy of the script document onCopy = () => { const copy = Doc.MakeCopy(this.rootDoc, true); copy.x = NumCast(this.dataDoc.x) + NumCast(this.dataDoc._width); this.props.addDocument?.(copy); } // adds option to create a copy to the context menu specificContextMenu = (): void => { const existingOptions = ContextMenu.Instance.findByDescription("Options..."); const options = existingOptions && "subitems" in existingOptions ? existingOptions.subitems : []; options.push({ description: "Create a Copy", event: this.onCopy, icon: "copy" }); !existingOptions && ContextMenu.Instance.addItem({ description: "Options...", subitems: options, icon: "hand-point-right" }); } renderFunctionInputs() { const descriptionInput =