aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/nodes/ScriptingBox.tsx
diff options
context:
space:
mode:
Diffstat (limited to 'src/client/views/nodes/ScriptingBox.tsx')
-rw-r--r--src/client/views/nodes/ScriptingBox.tsx346
1 files changed, 302 insertions, 44 deletions
diff --git a/src/client/views/nodes/ScriptingBox.tsx b/src/client/views/nodes/ScriptingBox.tsx
index 0944edf60..db8a8b559 100644
--- a/src/client/views/nodes/ScriptingBox.tsx
+++ b/src/client/views/nodes/ScriptingBox.tsx
@@ -1,19 +1,23 @@
-import { action, observable, computed } from "mobx";
+import { action, computed, observable } from "mobx";
import { observer } from "mobx-react";
import * as React from "react";
+import { Doc } from "../../../fields/Doc";
import { documentSchema } from "../../../fields/documentSchemas";
-import { createSchema, makeInterface, listSpec } from "../../../fields/Schema";
+import { List } from "../../../fields/List";
+import { createSchema, listSpec, makeInterface } from "../../../fields/Schema";
import { ScriptField } from "../../../fields/ScriptField";
-import { StrCast, ScriptCast, Cast } from "../../../fields/Types";
+import { Cast, NumCast, ScriptCast, StrCast } from "../../../fields/Types";
+import { returnEmptyString } from "../../../Utils";
+import { DragManager } from "../../util/DragManager";
import { InteractionUtils } from "../../util/InteractionUtils";
-import { CompileScript, isCompileError, ScriptParam } from "../../util/Scripting";
+import { CompileScript, ScriptParam } from "../../util/Scripting";
+import { ContextMenu } from "../ContextMenu";
import { ViewBoxAnnotatableComponent } from "../DocComponent";
import { EditableView } from "../EditableView";
import { FieldView, FieldViewProps } from "../nodes/FieldView";
-import "./ScriptingBox.scss";
import { OverlayView } from "../OverlayView";
import { DocumentIconContainer } from "./DocumentIcon";
-import { List } from "../../../fields/List";
+import "./ScriptingBox.scss";
const ScriptingSchema = createSchema({});
type ScriptingDocument = makeInterface<[typeof ScriptingSchema, typeof documentSchema]>;
@@ -21,41 +25,82 @@ const ScriptingDocument = makeInterface(ScriptingSchema, documentSchema);
@observer
export class ScriptingBox extends ViewBoxAnnotatableComponent<FieldViewProps, ScriptingDocument>(ScriptingDocument) {
+
+ private dropDisposer?: DragManager.DragDropDisposer;
protected multiTouchDisposer?: InteractionUtils.MultiTouchEventDisposer | undefined;
public static LayoutString(fieldStr: string) { return FieldView.LayoutString(ScriptingBox, fieldStr); }
-
- _overlayDisposer?: () => void;
+ private _overlayDisposer?: () => void;
@observable private _errorMessage: string = "";
+ @observable private _applied: boolean = false;
- @computed get rawScript() { return StrCast(this.dataDoc[this.props.fieldKey + "-rawScript"], StrCast(this.layoutDoc[this.props.fieldKey + "-rawScript"])); }
- @computed get compileParams() { return Cast(this.dataDoc[this.props.fieldKey + "-params"], listSpec("string"), Cast(this.layoutDoc[this.props.fieldKey + "-params"], listSpec("string"), [])); }
+ @computed get paramsNames() { return this.compileParams.map(p => p.split(":")[0].trim()); }
+ @computed get paramsTypes() { return this.compileParams.map(p => p.split(":")[1].trim()); }
+ @computed get rawScript() { return StrCast(this.dataDoc[this.props.fieldKey + "-rawScript"], ""); }
+ @computed get compileParams() { return Cast(this.dataDoc[this.props.fieldKey + "-params"], listSpec("string"), []); }
set rawScript(value) { this.dataDoc[this.props.fieldKey + "-rawScript"] = value; }
- set compileParams(value) { this.dataDoc[this.props.fieldKey + "-params"] = value; }
+ set compileParams(value) { this.dataDoc[this.props.fieldKey + "-params"] = new List<string>(value); }
@action
componentDidMount() {
- this.rawScript = ScriptCast(this.dataDoc[this.props.fieldKey])?.script?.originalScript || this.rawScript;
+ this.rawScript = ScriptCast(this.dataDoc[this.props.fieldKey])?.script?.originalScript ?? this.rawScript;
}
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);
+ }
+ }
+
+ @action
+ onFinish = () => {
+ this.rootDoc.layoutKey = "layout";
+ this.rootDoc._height = 50;
+ this.rootDoc._width = 100;
+ this.dataDoc.documentText = this.rawScript;
+ }
+
+ @action
+ onError = (error: any) => {
+ this._errorMessage = error?.map((entry: any) => entry.messageText).join(" ") || "";
+ }
+
@action
onCompile = () => {
- const params = this.compileParams.reduce((o: ScriptParam, p: string) => { o[p] = "any"; return o; }, {} as ScriptParam);
+ 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
+ typecheck: true
});
- this._errorMessage = isCompileError(result) ? result.errors.map(e => e.messageText).join("\n") : "";
- return this.dataDoc[this.props.fieldKey] = result.compiled ? new ScriptField(result) : undefined;
+ this.dataDoc.documentText = this.rawScript;
+ this.dataDoc.data = result.compiled ? new ScriptField(result) : undefined;
+ this.onError(result.compiled ? undefined : result.errors);
}
@action
onRun = () => {
- this.onCompile()?.script.run({}, err => this._errorMessage = err.map((e: any) => e.messageText).join("\n"));
+ this.onCompile();
+ const bindings: { [name: string]: any } = {};
+ this.paramsNames.forEach(key => bindings[key] = this.dataDoc[key]);
+ ScriptCast(this.dataDoc.data, null)?.script.run({ self: this.rootDoc, this: this.layoutDoc, ...bindings }, this.onError);
+ }
+
+ @action
+ onApply = () => {
+ this.onCompile();
+ this._applied = true;
+ }
+
+ @action
+ onEdit = () => {
+ this._applied = false;
}
onFocus = () => {
@@ -63,36 +108,249 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<FieldViewProps, Sc
this._overlayDisposer = OverlayView.Instance.addElement(<DocumentIconContainer />, { x: 0, y: 0 });
}
- render() {
- const params = <EditableView
- contents={this.compileParams.join(" ")}
- display={"block"}
- maxHeight={72}
- height={35}
- fontSize={28}
- GetValue={() => ""}
- SetValue={value => { this.compileParams = new List<string>(value.split(" ").filter(s => s !== " ")); return true; }}
+ @action
+ onDrop = (e: Event, de: DragManager.DropEvent, fieldKey: string) => {
+ this.dataDoc[fieldKey] = de.complete.docDragData?.droppedDocuments[0];
+ e.stopPropagation();
+ }
+
+ @action
+ onDelete = (num: number) => {
+ this.dataDoc[this.paramsNames[num]] = undefined;
+ this.compileParams.splice(num, 1);
+ return true;
+ }
+
+ @action
+ viewChanged = (e: React.ChangeEvent, name: string) => {
+ //@ts-ignore
+ this.dataDoc[name] = e.target.selectedOptions[0].value;
+ }
+
+ onCopy = () => {
+ const copy = Doc.MakeCopy(this.rootDoc, true);
+ copy.x = NumCast(this.dataDoc.x) + NumCast(this.dataDoc._width);
+ this.props.addDocument?.(copy);
+ }
+
+ specificContextMenu = (e: React.MouseEvent): 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" });
+ }
+
+ renderErrorMessage() {
+ return !this._errorMessage ? (null) : <div className="scriptingBox-errorMessage"> {this._errorMessage} </div>;
+ }
+
+ renderDoc(parameter: string) {
+ return <div className="scriptingBox-paramInputs" onFocus={this.onFocus} onBlur={e => this._overlayDisposer?.()}
+ ref={ele => ele && this.createDashEventsTarget(ele, (e, de) => this.onDrop(e, de, parameter))} >
+ <EditableView display={"block"} maxHeight={72} height={35} fontSize={14}
+ contents={this.dataDoc[parameter]?.title ?? ""}
+ GetValue={() => this.dataDoc[parameter]?.title ?? ""}
+ SetValue={action((value: string) => {
+ const script = CompileScript(value, {
+ addReturn: true,
+ typecheck: false,
+ transformer: DocumentIconContainer.getTransformer()
+ });
+ const results = script.compiled && script.run();
+ if (results && results.success) {
+ this._errorMessage = "";
+ this.dataDoc[parameter] = results.result;
+ return true;
+ }
+ this._errorMessage = "invalid document";
+ return false;
+ })}
+ />
+ </div>;
+ }
+
+ renderString(parameter: string) {
+ return <div className="scriptingBox-paramInputs">
+ <EditableView display={"block"} maxHeight={72} height={35} fontSize={14}
+ contents={this.dataDoc[parameter] ?? "undefined"}
+ GetValue={() => StrCast(this.dataDoc[parameter]) ?? "undefined"}
+ SetValue={action((value: string) => {
+ if (value && value !== " ") {
+ this._errorMessage = "";
+ this.dataDoc[parameter] = value;
+ return true;
+ }
+ return false;
+ })}
+ />
+ </div>;
+ }
+
+ renderNumber(parameter: string) {
+ return <div className="scriptingBox-paramInputs">
+ <EditableView display={"block"} maxHeight={72} height={35} fontSize={14}
+ contents={this.dataDoc[parameter] ?? "undefined"}
+ GetValue={() => StrCast(this.dataDoc[parameter]) ?? "undefined"}
+ SetValue={action((value: string) => {
+ if (value && value !== " ") {
+ if (parseInt(value)) {
+ this._errorMessage = "";
+ this.dataDoc[parameter] = parseInt(value);
+ return true;
+ }
+ this._errorMessage = "not a number";
+ }
+ return false;
+ })}
+ />
+ </div>;
+ }
+
+ renderEnum(parameter: string, types: string[]) {
+ return <div className="scriptingBox-paramInputs">
+ <div className="scriptingBox-viewBase">
+ <div className="commandEntry-outerDiv">
+ <select className="scriptingBox-viewPicker"
+ onPointerDown={e => e.stopPropagation()}
+ onChange={e => this.viewChanged(e, parameter)}
+ value={this.dataDoc[parameter]}>
+
+ {types.map(type =>
+ <option className="scriptingBox-viewOption" value={type.trim()}> {type.trim()} </option>
+ )}
+ </select>
+ </div>
+ </div>
+ </div>;
+ }
+
+ renderBoolean(parameter: string) {
+ return <div className="scriptingBox-paramInputs">
+ <div className="scriptingBox-viewBase">
+ <div className="commandEntry-outerDiv">
+ <select className="scriptingBox-viewPicker"
+ onPointerDown={e => e.stopPropagation()}
+ onChange={e => this.viewChanged(e, parameter)}
+ value={this.dataDoc[parameter]}>
+ <option className="scriptingBox-viewOption" value={"true"}>true </option>
+ <option className="scriptingBox-viewOption" value={"false"}>false</option>
+ </select>
+ </div>
+ </div>
+ </div>;
+ }
+
+ compileParam(value: string, whichParam?: number) {
+ if (value.includes(":")) {
+ const ptype = value.split(":")[1].trim();
+ const pname = value.split(":")[0].trim();
+ if (ptype === "Doc" || ptype === "string" || ptype === "number" || ptype === "boolean" || ptype.split("|")[1]) {
+ if ((whichParam !== undefined && pname === this.paramsNames[whichParam]) || !this.paramsNames.includes(pname)) {
+ this._errorMessage = "";
+ if (whichParam !== undefined) {
+ this.compileParams[whichParam] = value;
+ } else {
+ this.compileParams = [...value.split(";").filter(s => s), ...this.compileParams];
+ }
+ return true;
+ }
+ this._errorMessage = "this name has already been used";
+ } else {
+ this._errorMessage = "this type is not supported";
+ }
+ } else {
+ this._errorMessage = "must set type of parameter";
+ }
+ return false;
+ }
+
+ renderScriptingInputs() {
+ const parameterInput = <div className="scriptingBox-params">
+ <EditableView display={"block"} maxHeight={72} height={35} fontSize={22}
+ contents={""}
+ GetValue={returnEmptyString}
+ SetValue={value => value && value !== " " ? this.compileParam(value) : false}
+ />
+ </div>;
+
+ const scriptingInputText = <textarea onFocus={this.onFocus} onBlur={e => this._overlayDisposer?.()}
+ onChange={e => this.rawScript = e.target.value}
+ placeholder="write your script here"
+ value={this.rawScript}
+ style={{ width: this.compileParams.length > 0 ? "70%" : "100%", resize: "none", height: "100%" }}
/>;
+
+ const definedParameters = !this.compileParams.length ? (null) :
+ <div className="scriptingBox-plist" style={{ width: "30%" }}>
+ {this.compileParams.map((parameter, i) =>
+ <div className="scriptingBox-pborder" onKeyPress={e => e.key === "Enter" && this._overlayDisposer?.()} >
+ <EditableView display={"block"} maxHeight={72} height={35} fontSize={12}
+ contents={parameter}
+ GetValue={() => parameter}
+ SetValue={value => value && value !== " " ? this.compileParam(value, i) : this.onDelete(i)}
+ />
+ </div>
+ )}
+ </div>;
+
+ return <div className="scriptingBox-inputDiv" onPointerDown={e => this.props.isSelected() && e.stopPropagation()} >
+ <div className="scriptingBox-wrapper">
+ {scriptingInputText}
+ {definedParameters}
+ </div>
+ {parameterInput}
+ {this.renderErrorMessage()}
+ </div>;
+ }
+
+ renderScriptingTools() {
+ const buttonStyle = "scriptingBox-button" + (this.rootDoc.layoutKey === "layout_onClick" ? "third" : "");
+ return <div className="scriptingBox-toolbar">
+ <button className={buttonStyle} onPointerDown={e => { this.onCompile(); e.stopPropagation(); }}>Compile</button>
+ <button className={buttonStyle} onPointerDown={e => { this.onApply(); e.stopPropagation(); }}>Apply</button>
+ {this.rootDoc.layoutKey !== "layout_onClick" ? (null) :
+ <button className={buttonStyle} onPointerDown={e => { this.onFinish(); e.stopPropagation(); }}>Finish</button>}
+ </div>;
+ }
+
+ renderParamsInputs() {
+ return <div className="scriptingBox-inputDiv" onPointerDown={e => this.props.isSelected(true) && e.stopPropagation()} >
+ {!this.compileParams.length || !this.paramsNames ? (null) :
+ <div className="scriptingBox-plist">
+ {this.paramsNames.map((parameter: string, i: number) =>
+ <div className="scriptingBox-pborder" onKeyPress={e => e.key === "Enter" && this._overlayDisposer?.()} >
+ <div className="scriptingBox-wrapper">
+ <div className="scriptingBox-paramNames"> {`${parameter}:${this.paramsTypes[i]} = `} </div>
+ {this.paramsTypes[i] === "boolean" ? this.renderBoolean(parameter) : (null)}
+ {this.paramsTypes[i] === "string" ? this.renderString(parameter) : (null)}
+ {this.paramsTypes[i] === "number" ? this.renderNumber(parameter) : (null)}
+ {this.paramsTypes[i] === "Doc" ? this.renderDoc(parameter) : (null)}
+ {this.paramsTypes[i]?.split("|")[1] ? this.renderEnum(parameter, this.paramsTypes[i].split("|")) : (null)}
+ </div>
+ </div>)}
+ </div>}
+ </div>;
+ }
+
+ renderParamsTools() {
+ const buttonStyle = "scriptingBox-button" + (this.rootDoc.layoutKey === "layout_onClick" ? "third" : "");
+ return <div className="scriptingBox-toolbar">
+ {this.renderErrorMessage()}
+ <button className={buttonStyle} onPointerDown={e => { this.onEdit(); e.stopPropagation(); }}>Edit</button>
+ <button className={buttonStyle} onPointerDown={e => { this.onRun(); e.stopPropagation(); }}>Run</button>
+ {this.rootDoc.layoutKey !== "layout_onClick" ? (null) :
+ <button className={buttonStyle} onPointerDown={e => { this.onFinish(); e.stopPropagation(); }}>Finish</button>}
+ </div>;
+ }
+
+ render() {
return (
- <div className="scriptingBox-outerDiv"
- onWheel={e => this.props.isSelected(true) && e.stopPropagation()}>
- <div className="scriptingBox-inputDiv"
- onPointerDown={e => this.props.isSelected(true) && e.stopPropagation()} >
- <textarea className="scriptingBox-textarea"
- placeholder="write your script here"
- onChange={e => this.rawScript = e.target.value}
- value={this.rawScript}
- onFocus={this.onFocus}
- onBlur={e => this._overlayDisposer?.()} />
- <div className="scriptingBox-errorMessage" style={{ background: this._errorMessage ? "red" : "" }}>{this._errorMessage}</div>
- <div className="scriptingBox-params" >{params}</div>
- </div>
- {this.rootDoc.layout === "layout" ? <div></div> : (null)}
- <div className="scriptingBox-toolbar">
- <button className="scriptingBox-button" onPointerDown={e => { this.onCompile(); e.stopPropagation(); }}>Compile</button>
- <button className="scriptingBox-button" onPointerDown={e => { this.onRun(); e.stopPropagation(); }}>Run</button>
+ <div className={`scriptingBox`} onContextMenu={this.specificContextMenu}>
+ <div className="scriptingBox-outerDiv" onWheel={e => this.props.isSelected(true) && e.stopPropagation()}>
+ {!this._applied ? this.renderScriptingInputs() : this.renderParamsInputs()}
+ {!this._applied ? this.renderScriptingTools() : this.renderParamsTools()}
</div>
</div>
);
}
-}
+} \ No newline at end of file