workbenchEditor.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. import * as React from "react";
  2. import { GlobalState } from "./globalState";
  3. import { GuiListComponent } from "./components/guiList/guiListComponent";
  4. import { PropertyTabComponent } from "./components/propertyTab/propertyTabComponent";
  5. import { Portal } from "./portal";
  6. import { LogComponent } from "./components/log/logComponent";
  7. import { DataStorage } from "babylonjs/Misc/dataStorage";
  8. import { Nullable } from "babylonjs/types";
  9. import { GUINodeTools } from "./guiNodeTools";
  10. import { IEditorData } from "./nodeLocationInfo";
  11. import { WorkbenchComponent } from "./diagram/workbench";
  12. import { GUINode } from "./diagram/guiNode";
  13. import { _TypeStore } from "babylonjs/Misc/typeStore";
  14. import { MessageDialogComponent } from "./sharedComponents/messageDialog";
  15. import { Control } from "babylonjs-gui/2D/controls/control";
  16. import { Container } from "babylonjs-gui/2D/controls/container";
  17. require("./main.scss");
  18. interface IGraphEditorProps {
  19. globalState: GlobalState;
  20. }
  21. interface IGraphEditorState {
  22. showPreviewPopUp: boolean;
  23. }
  24. export class WorkbenchEditor extends React.Component<IGraphEditorProps, IGraphEditorState> {
  25. private _workbenchCanvas: WorkbenchComponent;
  26. private _startX: number;
  27. private _moveInProgress: boolean;
  28. private _leftWidth = DataStorage.ReadNumber("LeftWidth", 200);
  29. private _rightWidth = DataStorage.ReadNumber("RightWidth", 300);
  30. private _blocks = new Array<Container | Control>();
  31. private _onWidgetKeyUpPointer: any;
  32. private _popUpWindow: Window;
  33. /**
  34. * Creates a node and recursivly creates its parent nodes from it's input
  35. * @param block
  36. */
  37. public createNodeFromObject(block: Control, recursion = true) {
  38. if (this._blocks.indexOf(block) !== -1) {
  39. return this._workbenchCanvas.nodes.filter((n) => n.guiControl === block)[0];
  40. }
  41. this._blocks.push(block);
  42. //TODO: Implement
  43. const node = null;
  44. return node;
  45. }
  46. componentDidMount() {
  47. if (this.props.globalState.hostDocument) {
  48. this._workbenchCanvas = this.refs["graphCanvas"] as WorkbenchComponent;
  49. }
  50. if (navigator.userAgent.indexOf("Mobile") !== -1) {
  51. ((this.props.globalState.hostDocument || document).querySelector(".blocker") as HTMLElement).style.visibility = "visible";
  52. }
  53. }
  54. componentWillUnmount() {
  55. if (this.props.globalState.hostDocument) {
  56. this.props.globalState.hostDocument!.removeEventListener("keyup", this._onWidgetKeyUpPointer, false);
  57. }
  58. }
  59. constructor(props: IGraphEditorProps) {
  60. super(props);
  61. this.state = {
  62. showPreviewPopUp: false,
  63. };
  64. this.props.globalState.hostDocument!.addEventListener(
  65. "keydown",
  66. (evt) => {
  67. if ((evt.keyCode === 46 || evt.keyCode === 8) && !this.props.globalState.blockKeyboardEvents) {
  68. // Delete
  69. let selectedItems = this._workbenchCanvas.selectedGuiNodes;
  70. for (var selectedItem of selectedItems) {
  71. selectedItem.dispose();
  72. }
  73. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  74. return;
  75. }
  76. if (!evt.ctrlKey || this.props.globalState.blockKeyboardEvents) {
  77. return;
  78. }
  79. if (evt.key === "c") {
  80. // Copy
  81. let selectedItems = this._workbenchCanvas.selectedGuiNodes;
  82. if (!selectedItems.length) {
  83. return;
  84. }
  85. let selectedItem = selectedItems[0] as GUINode;
  86. if (!selectedItem.guiControl) {
  87. return;
  88. }
  89. } else if (evt.key === "v") {
  90. // Paste
  91. //TODO: Implement
  92. }
  93. },
  94. false
  95. );
  96. }
  97. pasteSelection(copiedNodes: GUINode[], currentX: number, currentY: number, selectNew = false) {
  98. //let originalNode: Nullable<GUINode> = null;
  99. let newNodes: GUINode[] = [];
  100. // Copy to prevent recursive side effects while creating nodes.
  101. copiedNodes = copiedNodes.slice();
  102. // Cancel selection
  103. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  104. // Create new nodes
  105. for (var node of copiedNodes) {
  106. let block = node.guiControl;
  107. if (!block) {
  108. continue;
  109. }
  110. }
  111. return newNodes;
  112. }
  113. zoomToFit() {
  114. this._workbenchCanvas.zoomToFit();
  115. }
  116. showWaitScreen() {
  117. this.props.globalState.hostDocument.querySelector(".wait-screen")?.classList.remove("hidden");
  118. }
  119. hideWaitScreen() {
  120. this.props.globalState.hostDocument.querySelector(".wait-screen")?.classList.add("hidden");
  121. }
  122. reOrganize(editorData: Nullable<IEditorData> = null, isImportingAFrame = false) {
  123. this.showWaitScreen();
  124. this._workbenchCanvas._isLoading = true; // Will help loading large graphes
  125. setTimeout(() => {
  126. if (!editorData || !editorData.locations) {
  127. this._workbenchCanvas.distributeGraph();
  128. } else {
  129. // Locations
  130. for (var location of editorData.locations) {
  131. for (var node of this._workbenchCanvas.nodes) {
  132. if (node.guiControl && node.guiControl.uniqueId === location.blockId) {
  133. node.x = location.x;
  134. node.y = location.y;
  135. node.cleanAccumulation();
  136. break;
  137. }
  138. }
  139. }
  140. }
  141. this._workbenchCanvas._isLoading = false;
  142. for (var node of this._workbenchCanvas.nodes) {
  143. }
  144. this.hideWaitScreen();
  145. });
  146. }
  147. onPointerDown(evt: React.PointerEvent<HTMLDivElement>) {
  148. this._startX = evt.clientX;
  149. this._moveInProgress = true;
  150. evt.currentTarget.setPointerCapture(evt.pointerId);
  151. }
  152. onPointerUp(evt: React.PointerEvent<HTMLDivElement>) {
  153. this._moveInProgress = false;
  154. evt.currentTarget.releasePointerCapture(evt.pointerId);
  155. }
  156. resizeColumns(evt: React.PointerEvent<HTMLDivElement>, forLeft = true) {
  157. if (!this._moveInProgress) {
  158. return;
  159. }
  160. const deltaX = evt.clientX - this._startX;
  161. const rootElement = evt.currentTarget.ownerDocument!.getElementById("workbench-editor-workbench-root") as HTMLDivElement;
  162. if (forLeft) {
  163. this._leftWidth += deltaX;
  164. this._leftWidth = Math.max(150, Math.min(400, this._leftWidth));
  165. DataStorage.WriteNumber("LeftWidth", this._leftWidth);
  166. } else {
  167. this._rightWidth -= deltaX;
  168. this._rightWidth = Math.max(250, Math.min(500, this._rightWidth));
  169. DataStorage.WriteNumber("RightWidth", this._rightWidth);
  170. rootElement.ownerDocument!.getElementById("preview")!.style.height = this._rightWidth + "px";
  171. }
  172. rootElement.style.gridTemplateColumns = this.buildColumnLayout();
  173. this._startX = evt.clientX;
  174. }
  175. buildColumnLayout() {
  176. return `${this._leftWidth}px 4px calc(100% - ${this._leftWidth + 8 + this._rightWidth}px) 4px ${this._rightWidth}px`;
  177. }
  178. emitNewBlock(event: React.DragEvent<HTMLDivElement>) {
  179. var data = event.dataTransfer.getData("babylonjs-gui-node") as string;
  180. let guiElement = GUINodeTools.CreateControlFromString (data);
  181. let newGuiNode = this._workbenchCanvas.appendBlock(guiElement);
  182. //TODO: Get correct positioning
  183. /*let x = event.clientX; // - event.currentTarget.offsetLeft - this._workbenchCanvas.x;
  184. let y = event.clientY; // - event.currentTarget.offsetTop - this._workbenchCanvas.y - 20;
  185. newGuiNode.x += (x - newGuiNode.x);
  186. newGuiNode.y += y - newGuiNode.y;
  187. //newGuiNode.cleanAccumulation();*/
  188. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  189. this.props.globalState.onSelectionChangedObservable.notifyObservers(newGuiNode);
  190. this.forceUpdate();
  191. }
  192. handlePopUp = () => {
  193. this.setState({
  194. showPreviewPopUp: true,
  195. });
  196. this.props.globalState.hostWindow.addEventListener("beforeunload", this.handleClosingPopUp);
  197. };
  198. handleClosingPopUp = () => {
  199. this._popUpWindow.close();
  200. };
  201. createPopupWindow = (title: string, windowVariableName: string, width = 500, height = 500): Window | null => {
  202. const windowCreationOptionsList = {
  203. width: width,
  204. height: height,
  205. top: (this.props.globalState.hostWindow.innerHeight - width) / 2 + window.screenY,
  206. left: (this.props.globalState.hostWindow.innerWidth - height) / 2 + window.screenX,
  207. };
  208. var windowCreationOptions = Object.keys(windowCreationOptionsList)
  209. .map((key) => key + "=" + (windowCreationOptionsList as any)[key])
  210. .join(",");
  211. const popupWindow = this.props.globalState.hostWindow.open("", title, windowCreationOptions);
  212. if (!popupWindow) {
  213. return null;
  214. }
  215. const parentDocument = popupWindow.document;
  216. parentDocument.title = title;
  217. parentDocument.body.style.width = "100%";
  218. parentDocument.body.style.height = "100%";
  219. parentDocument.body.style.margin = "0";
  220. parentDocument.body.style.padding = "0";
  221. let parentControl = parentDocument.createElement("div");
  222. parentControl.style.width = "100%";
  223. parentControl.style.height = "100%";
  224. parentControl.style.margin = "0";
  225. parentControl.style.padding = "0";
  226. parentControl.style.display = "grid";
  227. parentControl.style.gridTemplateRows = "40px auto";
  228. parentControl.id = "gui-editor-workbench-root";
  229. parentControl.className = "right-panel";
  230. popupWindow.document.body.appendChild(parentControl);
  231. this.copyStyles(this.props.globalState.hostWindow.document, parentDocument);
  232. (this as any)[windowVariableName] = popupWindow;
  233. this._popUpWindow = popupWindow;
  234. return popupWindow;
  235. };
  236. copyStyles = (sourceDoc: HTMLDocument, targetDoc: HTMLDocument) => {
  237. const styleContainer = [];
  238. for (var index = 0; index < sourceDoc.styleSheets.length; index++) {
  239. var styleSheet: any = sourceDoc.styleSheets[index];
  240. try {
  241. if (styleSheet.href) {
  242. // for <link> elements loading CSS from a URL
  243. const newLinkEl = sourceDoc.createElement("link");
  244. newLinkEl.rel = "stylesheet";
  245. newLinkEl.href = styleSheet.href;
  246. targetDoc.head!.appendChild(newLinkEl);
  247. styleContainer.push(newLinkEl);
  248. } else if (styleSheet.cssRules) {
  249. // for <style> elements
  250. const newStyleEl = sourceDoc.createElement("style");
  251. for (var cssRule of styleSheet.cssRules) {
  252. newStyleEl.appendChild(sourceDoc.createTextNode(cssRule.cssText));
  253. }
  254. targetDoc.head!.appendChild(newStyleEl);
  255. styleContainer.push(newStyleEl);
  256. }
  257. } catch (e) {
  258. console.log(e);
  259. }
  260. }
  261. };
  262. fixPopUpStyles = (document: Document) => {
  263. const previewContainer = document.getElementById("preview");
  264. if (previewContainer) {
  265. previewContainer.style.height = "auto";
  266. previewContainer.style.gridRow = "1";
  267. }
  268. const previewConfigBar = document.getElementById("preview-config-bar");
  269. if (previewConfigBar) {
  270. previewConfigBar.style.gridRow = "2";
  271. }
  272. const newWindowButton = document.getElementById("preview-new-window");
  273. if (newWindowButton) {
  274. newWindowButton.style.display = "none";
  275. }
  276. const previewMeshBar = document.getElementById("preview-mesh-bar");
  277. if (previewMeshBar) {
  278. previewMeshBar.style.gridTemplateColumns = "auto 1fr 40px 40px";
  279. }
  280. };
  281. render() {
  282. return (
  283. <Portal globalState={this.props.globalState}>
  284. <div
  285. id="gui-editor-workbench-root"
  286. style={{
  287. gridTemplateColumns: this.buildColumnLayout(),
  288. }}
  289. onMouseMove={(evt) => {
  290. // this._mouseLocationX = evt.pageX;
  291. // this._mouseLocationY = evt.pageY;
  292. }}
  293. onMouseDown={(evt) => {
  294. if ((evt.target as HTMLElement).nodeName === "INPUT") {
  295. return;
  296. }
  297. this.props.globalState.blockKeyboardEvents = false;
  298. }}
  299. >
  300. {/* Node creation menu */}
  301. <GuiListComponent globalState={this.props.globalState} />
  302. <div id="leftGrab" onPointerDown={(evt) => this.onPointerDown(evt)} onPointerUp={(evt) => this.onPointerUp(evt)} onPointerMove={(evt) => this.resizeColumns(evt)}></div>
  303. {/* The gui workbench diagram */}
  304. <div
  305. className="diagram-container"
  306. onDrop={(event) => {
  307. this.emitNewBlock(event);
  308. }}
  309. onDragOver={(event) => {
  310. event.preventDefault();
  311. }}
  312. >
  313. <WorkbenchComponent ref={"graphCanvas"} globalState={this.props.globalState} />
  314. </div>
  315. <div id="rightGrab" onPointerDown={(evt) => this.onPointerDown(evt)} onPointerUp={(evt) => this.onPointerUp(evt)} onPointerMove={(evt) => this.resizeColumns(evt, false)}></div>
  316. {/* Property tab */}
  317. <div className="right-panel">
  318. <PropertyTabComponent globalState={this.props.globalState} />
  319. </div>
  320. <LogComponent globalState={this.props.globalState} />
  321. </div>
  322. <MessageDialogComponent globalState={this.props.globalState} />
  323. <div className="blocker">Node Material Editor runs only on desktop</div>
  324. <div className="wait-screen hidden">Processing...please wait</div>
  325. </Portal>
  326. );
  327. }
  328. }