index.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. var jsEditor;
  2. (function () {
  3. var fontSize = 14;
  4. var splitInstance = Split(['#jsEditor', '#canvasZone']);
  5. var elementToTheme = [
  6. '.wrapper .gutter',
  7. '.wrapper #jsEditor',
  8. '.navbar',
  9. '.navbar .select .toDisplay .option',
  10. '.navbar .select .toDisplayBig',
  11. '.navbar .select .toDisplayBig a',
  12. '.navbar .select .toDisplayBig ul li',
  13. '.navbarBottom',
  14. '.navbarBottom .links .link',
  15. '.save-message'];
  16. var run = function () {
  17. var blockEditorChange = false;
  18. jsEditor.onKeyDown(function (evt) {
  19. });
  20. jsEditor.onKeyUp(function (evt) {
  21. if (blockEditorChange) {
  22. return;
  23. }
  24. document.getElementById("currentScript").innerHTML = "Custom";
  25. document.getElementById('safemodeToggle').classList.add('checked');
  26. });
  27. var snippetUrl = "https://babylonjs-api2.azurewebsites.net/snippets";
  28. var currentSnippetToken;
  29. var currentSnippetTitle = null;
  30. var currentSnippetDescription = null;
  31. var currentSnippetTags = null;
  32. var engine;
  33. var fpsLabel = document.getElementById("fpsLabel");
  34. var scripts;
  35. var zipCode;
  36. BABYLON.Engine.ShadersRepository = "/src/Shaders/";
  37. var currentVersionElement = document.getElementById("currentVersion");
  38. if (currentVersionElement) {
  39. switch (BABYLON.Engine.Version) {
  40. case "2.5":
  41. currentVersionElement.innerHTML = "Version: " + BABYLON.Engine.Version;
  42. break;
  43. default:
  44. currentVersionElement.innerHTML = "Version: Latest";
  45. break;
  46. }
  47. }
  48. var loadScript = function (scriptURL, title) {
  49. var xhr = new XMLHttpRequest();
  50. xhr.open('GET', scriptURL, true);
  51. xhr.onreadystatechange = function () {
  52. if (xhr.readyState === 4) {
  53. if (xhr.status === 200) {
  54. blockEditorChange = true;
  55. jsEditor.setValue(xhr.responseText);
  56. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  57. blockEditorChange = false;
  58. compileAndRun();
  59. document.getElementById("currentScript").innerHTML = title;
  60. currentSnippetToken = null;
  61. }
  62. }
  63. };
  64. xhr.send(null);
  65. };
  66. var loadScriptFromIndex = function (index) {
  67. if (index === 0) {
  68. index = 1;
  69. }
  70. var script = scripts[index - 1].trim();
  71. loadScript("scripts/" + script + ".js", script);
  72. }
  73. var onScriptClick = function (evt) {
  74. loadScriptFromIndex(evt.target.scriptLinkIndex);
  75. };
  76. var loadScriptsList = function () {
  77. var xhr = new XMLHttpRequest();
  78. xhr.open('GET', 'scripts/scripts.txt', true);
  79. xhr.onreadystatechange = function () {
  80. if (xhr.readyState === 4) {
  81. if (xhr.status === 200) {
  82. scripts = xhr.responseText.split("\n");
  83. var ul = document.getElementById("scriptsList");
  84. var index;
  85. for (index = 0; index < scripts.length; index++) {
  86. var option = document.createElement("li");
  87. var a = document.createElement("a");
  88. a.href = "#";
  89. a.innerHTML = (index + 1) + " - " + scripts[index];
  90. a.scriptLinkIndex = index + 1;
  91. a.onclick = onScriptClick;
  92. option.scriptLinkIndex = index + 1;
  93. option.onclick = onScriptClick;
  94. option.appendChild(a);
  95. ul.appendChild(option);
  96. }
  97. if (!location.hash) {
  98. // Query string
  99. var queryString = window.location.search;
  100. if (queryString) {
  101. var query = queryString.replace("?", "");
  102. index = parseInt(query);
  103. if (!isNaN(index)) {
  104. loadScriptFromIndex(index);
  105. } else {
  106. loadScript("scripts/" + query + ".js", query);
  107. }
  108. } else {
  109. loadScript("scripts/basic scene.js", "Basic scene");
  110. }
  111. }
  112. // Restore theme
  113. var theme = localStorage.getItem("bjs-playground-theme") || 'light';
  114. toggleTheme(theme);
  115. // Remove editor if window size is less than 850px
  116. var removeEditorForSmallScreen = function () {
  117. if (mq.matches) {
  118. splitInstance.collapse(0);
  119. } else {
  120. splitInstance.setSizes([50, 50]);
  121. }
  122. }
  123. var mq = window.matchMedia("(max-width: 850px)");
  124. mq.addListener(removeEditorForSmallScreen);
  125. }
  126. }
  127. };
  128. xhr.send(null);
  129. }
  130. var createNewScript = function () {
  131. location.hash = "";
  132. currentSnippetToken = null;
  133. currentSnippetTitle = null;
  134. currentSnippetDescription = null;
  135. currentSnippetTags = null;
  136. showNoMetadata();
  137. jsEditor.setValue('// You have to create a function called createScene. This function must return a BABYLON.Scene object\r\n// You can reference the following variables: scene, canvas\r\n// You must at least define a camera\r\n// More info here: https://doc.babylonjs.com/generals/The_Playground_Tutorial\r\n\r\nvar createScene = function() {\r\n\tvar scene = new BABYLON.Scene(engine);\r\n\tvar camera = new BABYLON.ArcRotateCamera("Camera", 0, Math.PI / 2, 12, BABYLON.Vector3.Zero(), scene);\r\n\tcamera.attachControl(canvas, true);\r\n\r\n\r\n\r\n\treturn scene;\r\n};');
  138. jsEditor.setPosition({ lineNumber: 11, column: 0 });
  139. jsEditor.focus();
  140. compileAndRun();
  141. }
  142. var clear = function () {
  143. location.hash = "";
  144. currentSnippetToken = null;
  145. jsEditor.setValue('');
  146. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  147. jsEditor.focus();
  148. }
  149. var showError = function (errorMessage, errorEvent) {
  150. var errorContent =
  151. '<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;</button>';
  152. if (errorEvent) {
  153. var regEx = /\(.+:(\d+):(\d+)\)\n/g;
  154. var match = regEx.exec(errorEvent.stack);
  155. if (match) {
  156. errorContent += "Line ";
  157. var lineNumber = match[1];
  158. var columnNumber = match[2];
  159. errorContent += lineNumber + ':' + columnNumber + ' - ';
  160. }
  161. }
  162. errorContent += errorMessage + '</div>';
  163. document.getElementById("errorZone").style.display = 'block';
  164. document.getElementById("errorZone").innerHTML = errorContent;
  165. // Close button error
  166. document.getElementById("errorZone").querySelector('.close').addEventListener('click', function () {
  167. document.getElementById("errorZone").style.display = 'none';
  168. });
  169. }
  170. var showNoMetadata = function () {
  171. document.getElementById("saveFormTitle").value = '';
  172. document.getElementById("saveFormTitle").readOnly = false;
  173. document.getElementById("saveFormDescription").value = '';
  174. document.getElementById("saveFormDescription").readOnly = false;
  175. document.getElementById("saveFormTags").value = '';
  176. document.getElementById("saveFormTags").readOnly = false;
  177. document.getElementById("saveFormButtons").style.display = "block";
  178. document.getElementById("saveFormButtonOk").style.display = "inline-block";
  179. document.getElementById("saveMessage").style.display = "block";
  180. // document.getElementById("metadataButton").style.display = "none";
  181. };
  182. showNoMetadata();
  183. document.getElementById("saveMessage").style.display = "none";
  184. var hideNoMetadata = function () {
  185. document.getElementById("saveFormTitle").readOnly = true;
  186. document.getElementById("saveFormDescription").readOnly = true;
  187. document.getElementById("saveFormTags").readOnly = true;
  188. document.getElementById("saveFormButtonOk").style.display = "none";
  189. document.getElementById("saveMessage").style.display = "none";
  190. document.getElementById("metadataButton").style.display = "block";
  191. };
  192. compileAndRun = function () {
  193. try {
  194. if (!BABYLON.Engine.isSupported()) {
  195. showError("Your browser does not support WebGL", null);
  196. return;
  197. }
  198. if (engine) {
  199. engine.dispose();
  200. engine = null;
  201. }
  202. var canvas = document.getElementById("renderCanvas");
  203. engine = new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true });
  204. document.getElementById("errorZone").style.display = 'none';
  205. document.getElementById("errorZone").innerHTML = "";
  206. document.getElementById("statusBar").innerHTML = "Loading assets...Please wait";
  207. engine.runRenderLoop(function () {
  208. if (engine.scenes.length === 0) {
  209. return;
  210. }
  211. if (canvas.width !== canvas.clientWidth) {
  212. engine.resize();
  213. }
  214. var scene = engine.scenes[0];
  215. if (scene.activeCamera || scene.activeCameras.length > 0) {
  216. scene.render();
  217. }
  218. fpsLabel.innerHTML = engine.getFps().toFixed() + " fps";
  219. });
  220. var code = jsEditor.getValue();
  221. var scene;
  222. if (code.indexOf("createScene") !== -1) { // createScene
  223. eval(code);
  224. scene = createScene();
  225. if (!scene) {
  226. showError("createScene function must return a scene.", null);
  227. return;
  228. }
  229. zipCode = code + "\r\n\r\nvar scene = createScene();";
  230. } else if (code.indexOf("CreateScene") !== -1) { // CreateScene
  231. eval(code);
  232. scene = CreateScene();
  233. if (!scene) {
  234. showError("CreateScene function must return a scene.", null);
  235. return;
  236. }
  237. zipCode = code + "\r\n\r\nvar scene = CreateScene();";
  238. } else if (code.indexOf("createscene") !== -1) { // createscene
  239. eval(code);
  240. scene = createscene();
  241. if (!scene) {
  242. showError("createscene function must return a scene.", null);
  243. return;
  244. }
  245. zipCode = code + "\r\n\r\nvar scene = createscene();";
  246. } else { // Direct code
  247. scene = new BABYLON.Scene(engine);
  248. eval("runScript = function(scene, canvas) {" + code + "}");
  249. runScript(scene, canvas);
  250. zipCode = "var scene = new BABYLON.Scene(engine);\r\n\r\n" + code;
  251. }
  252. if (engine.scenes.length === 0) {
  253. showError("You must at least create a scene.", null);
  254. return;
  255. }
  256. if (engine.scenes[0].activeCamera == null) {
  257. showError("You must at least create a camera.", null);
  258. return;
  259. }
  260. engine.scenes[0].executeWhenReady(function () {
  261. document.getElementById("statusBar").innerHTML = "";
  262. });
  263. } catch (e) {
  264. showError(e.message, e);
  265. }
  266. };
  267. window.addEventListener("resize",
  268. function () {
  269. if (engine) {
  270. engine.resize();
  271. }
  272. });
  273. // Load scripts list
  274. loadScriptsList();
  275. // Zip
  276. var addContentToZip = function (zip, name, url, replace, buffer, then) {
  277. var xhr = new XMLHttpRequest();
  278. xhr.open('GET', url, true);
  279. if (buffer) {
  280. xhr.responseType = "arraybuffer";
  281. }
  282. xhr.onreadystatechange = function () {
  283. if (xhr.readyState === 4) {
  284. if (xhr.status === 200) {
  285. var text;
  286. if (!buffer) {
  287. if (replace) {
  288. var splits = replace.split("\r\n");
  289. for (var index = 0; index < splits.length; index++) {
  290. splits[index] = " " + splits[index];
  291. }
  292. replace = splits.join("\r\n");
  293. text = xhr.responseText.replace("####INJECT####", replace);
  294. } else {
  295. text = xhr.responseText;
  296. }
  297. }
  298. zip.file(name, buffer ? xhr.response : text);
  299. then();
  300. }
  301. }
  302. };
  303. xhr.send(null);
  304. }
  305. var addTexturesToZip = function (zip, index, textures, folder, then) {
  306. if (index === textures.length) {
  307. then();
  308. return;
  309. }
  310. if (textures[index].isRenderTarget || textures[index] instanceof BABYLON.DynamicTexture) {
  311. addTexturesToZip(zip, index + 1, textures, folder, then);
  312. return;
  313. }
  314. if (textures[index].isCube) {
  315. if (textures[index]._extensions) {
  316. for (var i = 0; i < 6; i++) {
  317. textures.push({ name: textures[index].name + textures[index]._extensions[i] });
  318. }
  319. }
  320. else {
  321. textures.push({ name: textures[index].name });
  322. }
  323. addTexturesToZip(zip, index + 1, textures, folder, then);
  324. return;
  325. }
  326. if (folder == null) {
  327. folder = zip.folder("textures");
  328. }
  329. var url;
  330. if (textures[index].video) {
  331. url = textures[index].video.currentSrc;
  332. } else {
  333. url = textures[index].name;
  334. }
  335. var name = url.substr(url.lastIndexOf("/") + 1);
  336. addContentToZip(folder,
  337. name,
  338. url,
  339. null,
  340. true,
  341. function () {
  342. addTexturesToZip(zip, index + 1, textures, folder, then);
  343. });
  344. }
  345. var addImportedFilesToZip = function (zip, index, importedFiles, folder, then) {
  346. if (index === importedFiles.length) {
  347. then();
  348. return;
  349. }
  350. if (!folder) {
  351. folder = zip.folder("scenes");
  352. }
  353. var url = importedFiles[index];
  354. var name = url.substr(url.lastIndexOf("/") + 1);
  355. addContentToZip(folder,
  356. name,
  357. url,
  358. null,
  359. true,
  360. function () {
  361. addImportedFilesToZip(zip, index + 1, importedFiles, folder, then);
  362. });
  363. }
  364. var getZip = function () {
  365. if (engine.scenes.length === 0) {
  366. return;
  367. }
  368. var zip = new JSZip();
  369. var scene = engine.scenes[0];
  370. var textures = scene.textures;
  371. var importedFiles = scene.importedMeshesFiles;
  372. document.getElementById("statusBar").innerHTML = "Creating archive...Please wait";
  373. if (zipCode.indexOf("textures/worldHeightMap.jpg") !== -1) {
  374. textures.push({ name: "textures/worldHeightMap.jpg" });
  375. }
  376. addContentToZip(zip,
  377. "index.html",
  378. "zipContent/index.html",
  379. zipCode,
  380. false,
  381. function () {
  382. addTexturesToZip(zip,
  383. 0,
  384. textures,
  385. null,
  386. function () {
  387. addImportedFilesToZip(zip,
  388. 0,
  389. importedFiles,
  390. null,
  391. function () {
  392. var blob = zip.generate({ type: "blob" });
  393. saveAs(blob, "sample.zip");
  394. document.getElementById("statusBar").innerHTML = "";
  395. });
  396. });
  397. });
  398. }
  399. // Versions
  400. setVersion = function (version) {
  401. switch (version) {
  402. case "2.5":
  403. location.href = "index2_5.html" + location.hash;
  404. break;
  405. default:
  406. location.href = "index.html" + location.hash;
  407. break;
  408. }
  409. }
  410. // Fonts
  411. setFontSize = function (size) {
  412. fontSize = size;
  413. document.querySelector(".view-lines").style.fontSize = size + "px";
  414. document.getElementById("currentFontSize").innerHTML = "Font: " + size;
  415. };
  416. // Fullscreen
  417. var goFullscreen = function () {
  418. if (engine) {
  419. engine.switchFullscreen(true);
  420. }
  421. }
  422. var toggleEditor = function () {
  423. var editorButton = document.getElementById("editorButton");
  424. var scene = engine.scenes[0];
  425. // If the editor is present
  426. if (editorButton.classList.contains('checked')) {
  427. editorButton.classList.remove('checked');
  428. splitInstance.collapse(0);
  429. editorButton.innerHTML = 'Editor <i class="fa fa-square-o" aria-hidden="true"></i>';
  430. } else {
  431. editorButton.classList.add('checked');
  432. splitInstance.setSizes([50, 50]); // Reset
  433. editorButton.innerHTML = 'Editor <i class="fa fa-check-square" aria-hidden="true"></i>';
  434. }
  435. engine.resize();
  436. if (scene.debugLayer.isVisible()) {
  437. scene.debugLayer.hide();
  438. scene.debugLayer.show();
  439. }
  440. }
  441. /**
  442. * Toggle the dark theme
  443. */
  444. var toggleTheme = function (theme) {
  445. // Monaco
  446. var vsTheme;
  447. if (theme == 'dark') {
  448. vsTheme = 'vs-dark'
  449. } else {
  450. vsTheme = 'vs'
  451. }
  452. let oldCode = jsEditor.getValue();
  453. jsEditor.dispose();
  454. jsEditor = monaco.editor.create(document.getElementById('jsEditor'), {
  455. value: "",
  456. language: "javascript",
  457. lineNumbers: true,
  458. tabSize: "auto",
  459. insertSpaces: "auto",
  460. roundedSelection: true,
  461. scrollBeyondLastLine: false,
  462. automaticLayout: true,
  463. readOnly: false,
  464. theme: vsTheme,
  465. contextmenu: false
  466. });
  467. jsEditor.setValue(oldCode);
  468. setFontSize(fontSize);
  469. for (var index = 0; index < elementToTheme.length; index++) {
  470. var obj = elementToTheme[index];
  471. let domObjArr = document.querySelectorAll(obj);
  472. for (var domObjIndex = 0; domObjIndex < domObjArr.length; domObjIndex++) {
  473. var domObj = domObjArr[domObjIndex];
  474. domObj.classList.remove('light');
  475. domObj.classList.remove('dark');
  476. domObj.classList.add(theme);
  477. }
  478. }
  479. localStorage.setItem("bjs-playground-theme", theme);
  480. }
  481. var toggleDebug = function () {
  482. var debugButton = document.getElementById("debugButton");
  483. var scene = engine.scenes[0];
  484. if (debugButton.classList.contains('uncheck')) {
  485. debugButton.classList.remove('uncheck');
  486. scene.debugLayer.show();
  487. } else {
  488. debugButton.classList.add('uncheck');
  489. scene.debugLayer.hide();
  490. }
  491. }
  492. var toggleMetadata = function () {
  493. // var metadataButton = document.getElementById("metadataButton");
  494. var scene = engine.scenes[0];
  495. // metadataButton.classList.add('checked');
  496. document.getElementById("saveLayer").style.display = "block";
  497. }
  498. // UI
  499. document.getElementById("runButton").addEventListener("click", compileAndRun);
  500. document.getElementById("zipButton").addEventListener("click", getZip);
  501. document.getElementById("fullscreenButton").addEventListener("click", goFullscreen);
  502. document.getElementById("newButton").addEventListener("click", createNewScript);
  503. document.getElementById("clearButton").addEventListener("click", clear);
  504. document.getElementById("editorButton").addEventListener("click", toggleEditor);
  505. document.getElementById("debugButton").addEventListener("click", toggleDebug);
  506. document.getElementById("metadataButton").addEventListener("click", toggleMetadata);
  507. document.getElementById("darkTheme").addEventListener("click", toggleTheme.bind(this, 'dark'));
  508. document.getElementById("lightTheme").addEventListener("click", toggleTheme.bind(this, 'light'));
  509. // Restore theme
  510. var theme = localStorage.getItem("bjs-playground-theme") || 'light';
  511. toggleTheme(theme);
  512. //Navigation Overwrites
  513. var exitPrompt = function (e) {
  514. var safeToggle = document.getElementById("safemodeToggle");
  515. if (safeToggle.classList.contains('checked')) {
  516. e = e || window.event;
  517. var message =
  518. 'This page is asking you to confirm that you want to leave - data you have entered may not be saved.';
  519. if (e) {
  520. e.returnValue = message;
  521. }
  522. return message;
  523. }
  524. };
  525. window.onbeforeunload = exitPrompt;
  526. // Snippet
  527. var save = function () {
  528. // Retrieve title if necessary
  529. if (document.getElementById("saveLayer")) {
  530. currentSnippetTitle = document.getElementById("saveFormTitle").value;
  531. currentSnippetDescription = document.getElementById("saveFormDescription").value;
  532. currentSnippetTags = document.getElementById("saveFormTags").value;
  533. }
  534. var xmlHttp = new XMLHttpRequest();
  535. xmlHttp.onreadystatechange = function () {
  536. if (xmlHttp.readyState === 4) {
  537. if (xmlHttp.status === 201) {
  538. var baseUrl = location.href.replace(location.hash, "").replace(location.search, "");
  539. var snippet = JSON.parse(xmlHttp.responseText);
  540. var newUrl = baseUrl + "#" + snippet.id;
  541. currentSnippetToken = snippet.id;
  542. if (snippet.version && snippet.version !== "0") {
  543. newUrl += "#" + snippet.version;
  544. }
  545. location.href = newUrl;
  546. // Hide the complete title & co message
  547. hideNoMetadata();
  548. compileAndRun();
  549. } else {
  550. showError("Unable to save your code. It may be too long.", null);
  551. }
  552. }
  553. }
  554. xmlHttp.open("POST", snippetUrl + (currentSnippetToken ? "/" + currentSnippetToken : ""), true);
  555. xmlHttp.setRequestHeader("Content-Type", "application/json");
  556. var dataToSend = {
  557. payload: {
  558. code: jsEditor.getValue()
  559. },
  560. name: currentSnippetTitle,
  561. description: currentSnippetDescription,
  562. tags: currentSnippetTags
  563. };
  564. xmlHttp.send(JSON.stringify(dataToSend));
  565. }
  566. document.getElementById("saveButton").addEventListener("click", function () {
  567. if (currentSnippetTitle == null
  568. && currentSnippetDescription == null
  569. && currentSnippetTags == null) {
  570. document.getElementById("saveLayer").style.display = "block";
  571. }
  572. else {
  573. save();
  574. }
  575. });
  576. document.getElementById("saveFormButtonOk").addEventListener("click", function () {
  577. document.getElementById("saveLayer").style.display = "none";
  578. save();
  579. });
  580. document.getElementById("saveFormButtonCancel").addEventListener("click", function () {
  581. document.getElementById("saveLayer").style.display = "none";
  582. });
  583. document.getElementById("saveMessage").addEventListener("click", function () {
  584. document.getElementById("saveMessage").style.display = "none";
  585. });
  586. document.getElementById("mainTitle").innerHTML = "v" + BABYLON.Engine.Version;
  587. var previousHash = "";
  588. var cleanHash = function () {
  589. var splits = decodeURIComponent(location.hash.substr(1)).split("#");
  590. if (splits.length > 2) {
  591. splits.splice(2, splits.length - 2);
  592. }
  593. location.hash = splits.join("#");
  594. }
  595. var checkHash = function (firstTime) {
  596. if (location.hash) {
  597. if (previousHash !== location.hash) {
  598. cleanHash();
  599. previousHash = location.hash;
  600. try {
  601. var xmlHttp = new XMLHttpRequest();
  602. xmlHttp.onreadystatechange = function () {
  603. if (xmlHttp.readyState === 4) {
  604. if (xmlHttp.status === 200) {
  605. var snippet = JSON.parse(xmlHttp.responseText)[0];
  606. blockEditorChange = true;
  607. jsEditor.setValue(JSON.parse(snippet.jsonPayload).code.toString());
  608. // Check if title / descr / tags are already set
  609. if ((snippet.name != null && snippet.name != "")
  610. || (snippet.description != null && snippet.description != "")
  611. || (snippet.tags != null && snippet.tags != "")) {
  612. currentSnippetTitle = snippet.name;
  613. currentSnippetDescription = snippet.description;
  614. currentSnippetTags = snippet.tags;
  615. if (document.getElementById("saveLayer")) {
  616. var elem = document.getElementById("saveLayer");
  617. document.getElementById("saveFormTitle").value = currentSnippetTitle;
  618. document.getElementById("saveFormDescription").value = currentSnippetDescription;
  619. document.getElementById("saveFormTags").value = currentSnippetTags;
  620. hideNoMetadata();
  621. }
  622. }
  623. else {
  624. currentSnippetTitle = null;
  625. currentSnippetDescription = null;
  626. currentSnippetTags = null;
  627. showNoMetadata();
  628. }
  629. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  630. blockEditorChange = false;
  631. compileAndRun();
  632. document.getElementById("currentScript").innerHTML = "Custom";
  633. } else if (firstTime) {
  634. location.href = location.href.replace(location.hash, "");
  635. if (scripts) {
  636. loadScriptFromIndex(0);
  637. }
  638. }
  639. }
  640. };
  641. var hash = location.hash.substr(1);
  642. currentSnippetToken = hash.split("#")[0];
  643. if (!hash.split("#")[1]) hash += "#0";
  644. xmlHttp.open("GET", snippetUrl + "/" + hash.replace("#", "/"));
  645. xmlHttp.send();
  646. } catch (e) {
  647. }
  648. }
  649. }
  650. setTimeout(checkHash, 200);
  651. }
  652. checkHash(true);
  653. }
  654. // Monaco
  655. var xhr = new XMLHttpRequest();
  656. xhr.open('GET', "babylon.d.txt", true);
  657. xhr.onreadystatechange = function () {
  658. if (xhr.readyState === 4) {
  659. if (xhr.status === 200) {
  660. require.config({ paths: { 'vs': 'node_modules/monaco-editor/min/vs' } });
  661. require(['vs/editor/editor.main'], function () {
  662. monaco.languages.typescript.javascriptDefaults.addExtraLib(xhr.responseText, 'babylon.d.ts');
  663. jsEditor = monaco.editor.create(document.getElementById('jsEditor'), {
  664. value: "",
  665. language: "javascript",
  666. lineNumbers: true,
  667. tabSize: "auto",
  668. insertSpaces: "auto",
  669. roundedSelection: true,
  670. scrollBeyondLastLine: false,
  671. automaticLayout: true,
  672. readOnly: false,
  673. theme: "vs",
  674. contextmenu: false
  675. });
  676. run();
  677. });
  678. }
  679. }
  680. };
  681. xhr.send(null);
  682. })();