nodeEditor.ts 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import * as React from "react";
  2. import * as ReactDOM from "react-dom";
  3. import { GlobalState } from './globalState';
  4. import { GraphEditor } from './graphEditor';
  5. import { NodeMaterial } from "babylonjs/Materials/Node/nodeMaterial"
  6. import { Popup } from "../src/sharedComponents/popup"
  7. import { SerializationTools } from './serializationTools';
  8. import { Observable } from 'babylonjs/Misc/observable';
  9. /**
  10. * Interface used to specify creation options for the node editor
  11. */
  12. export interface INodeEditorOptions {
  13. nodeMaterial: NodeMaterial,
  14. hostElement?: HTMLElement,
  15. customSave?: {label: string, action: (data: string) => Promise<void>};
  16. customLoadObservable?: Observable<any>
  17. }
  18. /**
  19. * Class used to create a node editor
  20. */
  21. export class NodeEditor {
  22. private static _CurrentState: GlobalState;
  23. /**
  24. * Show the node editor
  25. * @param options defines the options to use to configure the node editor
  26. */
  27. public static Show(options: INodeEditorOptions) {
  28. if (this._CurrentState) {
  29. var popupWindow = (Popup as any)["node-editor"];
  30. if (popupWindow) {
  31. popupWindow.close();
  32. }
  33. }
  34. let hostElement = options.hostElement;
  35. if (!hostElement) {
  36. hostElement = Popup.CreatePopup("BABYLON.JS NODE EDITOR", "node-editor", 1000, 800)!;
  37. }
  38. let globalState = new GlobalState();
  39. globalState.nodeMaterial = options.nodeMaterial;
  40. globalState.hostElement = hostElement;
  41. globalState.hostDocument = hostElement.ownerDocument!;
  42. globalState.customSave = options.customSave;
  43. globalState.hostWindow = hostElement.ownerDocument!.defaultView!;
  44. const graphEditor = React.createElement(GraphEditor, {
  45. globalState: globalState
  46. });
  47. ReactDOM.render(graphEditor, hostElement);
  48. if (options.customLoadObservable) {
  49. options.customLoadObservable.add(data => {
  50. SerializationTools.Deserialize(data, globalState);
  51. globalState.onBuiltObservable.notifyObservers();
  52. })
  53. }
  54. this._CurrentState = globalState;
  55. // Close the popup window when the page is refreshed or scene is disposed
  56. var popupWindow = (Popup as any)["node-editor"];
  57. if (globalState.nodeMaterial && popupWindow) {
  58. globalState.nodeMaterial.getScene().onDisposeObservable.addOnce(() => {
  59. if (popupWindow) {
  60. popupWindow.close();
  61. }
  62. })
  63. window.onbeforeunload = () => {
  64. var popupWindow = (Popup as any)["node-editor"];
  65. if (popupWindow) {
  66. popupWindow.close();
  67. }
  68. };
  69. }
  70. }
  71. }