nodeEditor.ts 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 { Observable } from 'babylonjs';
  8. import { SerializationTools } from './serializationTools';
  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) => 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. const graphEditor = React.createElement(GraphEditor, {
  44. globalState: globalState
  45. });
  46. ReactDOM.render(graphEditor, hostElement);
  47. if (options.customLoadObservable) {
  48. options.customLoadObservable.add(data => {
  49. SerializationTools.Deserialize(data, globalState);
  50. })
  51. }
  52. this._CurrentState = globalState;
  53. // Close the popup window when the page is refreshed or scene is disposed
  54. var popupWindow = (Popup as any)["node-editor"];
  55. if (globalState.nodeMaterial && popupWindow) {
  56. globalState.nodeMaterial.getScene().onDisposeObservable.addOnce(() => {
  57. if (popupWindow) {
  58. popupWindow.close();
  59. }
  60. })
  61. window.onbeforeunload = function(event) {
  62. var popupWindow = (Popup as any)["node-editor"];
  63. if (popupWindow) {
  64. popupWindow.close();
  65. }
  66. };
  67. }
  68. }
  69. }