editor.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. (function() { // eslint-disable-line
  2. 'use strict'; // eslint-disable-line
  3. /* global monaco, require */
  4. const lessonHelperScriptRE = /<script src="[^"]+threejs-lessons-helper\.js"><\/script>/;
  5. function getQuery(s) {
  6. s = s === undefined ? window.location.search : s;
  7. if (s[0] === '?' ) {
  8. s = s.substring(1);
  9. }
  10. const query = {};
  11. s.split('&').forEach(function(pair) {
  12. const parts = pair.split('=').map(decodeURIComponent);
  13. query[parts[0]] = parts[1];
  14. });
  15. return query;
  16. }
  17. function getSearch(url) {
  18. // yea I know this is not perfect but whatever
  19. const s = url.indexOf('?');
  20. return s < 0 ? {} : getQuery(url.substring(s));
  21. }
  22. const getFQUrl = (function() {
  23. const a = document.createElement('a');
  24. return function getFQUrl(url) {
  25. a.href = url;
  26. return a.href;
  27. };
  28. }());
  29. function getHTML(url, callback) {
  30. const req = new XMLHttpRequest();
  31. req.open('GET', url, true);
  32. req.addEventListener('load', function() {
  33. const success = req.status === 200 || req.status === 0;
  34. callback(success ? null : 'could not load: ' + url, req.responseText);
  35. });
  36. req.addEventListener('timeout', function() {
  37. callback('timeout get: ' + url);
  38. });
  39. req.addEventListener('error', function() {
  40. callback('error getting: ' + url);
  41. });
  42. req.send('');
  43. }
  44. function getPrefix(url) {
  45. const u = new URL(window.location.origin + url);
  46. const prefix = u.origin + dirname(u.pathname);
  47. return prefix;
  48. }
  49. function fixSourceLinks(url, source) {
  50. const srcRE = /(src=)"(.*?)"/g;
  51. const linkRE = /(href=)"(.*?")/g;
  52. const imageSrcRE = /((?:image|img)\.src = )"(.*?)"/g;
  53. const loaderLoadRE = /(loader.load[a-z]*\()('|")(.*?)('|")/ig;
  54. const urlPropRE = /(url:\s*)('|")(.*?)('|")/g;
  55. const prefix = getPrefix(url);
  56. function addPrefix(url) {
  57. return url.indexOf('://') < 0 ? (prefix + url) : url;
  58. }
  59. function makeLinkFQed(match, p1, url) {
  60. return p1 + '"' + addPrefix(url) + '"';
  61. }
  62. function makeLinkFDedQuotes(match, fn, q1, url, q2) {
  63. return fn + q1 + addPrefix(url) + q2;
  64. }
  65. source = source.replace(srcRE, makeLinkFQed);
  66. source = source.replace(linkRE, makeLinkFQed);
  67. source = source.replace(imageSrcRE, makeLinkFQed);
  68. source = source.replace(urlPropRE, makeLinkFDedQuotes);
  69. source = source.replace(loaderLoadRE, makeLinkFDedQuotes);
  70. return source;
  71. }
  72. const g = {
  73. html: '',
  74. };
  75. const htmlParts = {
  76. js: {
  77. language: 'javascript',
  78. },
  79. css: {
  80. language: 'css',
  81. },
  82. html: {
  83. language: 'html',
  84. },
  85. };
  86. function forEachHTMLPart(fn) {
  87. Object.keys(htmlParts).forEach(function(name, ndx) {
  88. const info = htmlParts[name];
  89. fn(info, ndx, name);
  90. });
  91. }
  92. function getHTMLPart(re, obj, tag) {
  93. let part = '';
  94. obj.html = obj.html.replace(re, function(p0, p1) {
  95. part = p1;
  96. return tag;
  97. });
  98. return part.replace(/\s*/, '');
  99. }
  100. function parseHTML(url, html) {
  101. html = fixSourceLinks(url, html);
  102. html = html.replace(/<div class="description">[^]*?<\/div>/, '');
  103. const styleRE = /<style>([^]*?)<\/style>/i;
  104. const titleRE = /<title>([^]*?)<\/title>/i;
  105. const bodyRE = /<body>([^]*?)<\/body>/i;
  106. const inlineScriptRE = /<script>([^]*?)<\/script>/i;
  107. const externalScriptRE = /(<!--(?:(?!-->)[\s\S])*?-->\n){0,1}<script\s*src\s*=\s*"(.*?)"\s*>\s*<\/script>/ig;
  108. const dataScriptRE = /(<!--(?:(?!-->)[\s\S])*?-->\n){0,1}<script (.*?)>([^]*?)<\/script>/ig;
  109. const cssLinkRE = /<link ([^>]+?)>/g;
  110. const isCSSLinkRE = /type="text\/css"|rel="stylesheet"/;
  111. const hrefRE = /href="([^"]+)"/;
  112. const obj = { html: html };
  113. htmlParts.css.source = getHTMLPart(styleRE, obj, '<style>\n${css}</style>');
  114. htmlParts.html.source = getHTMLPart(bodyRE, obj, '<body>${html}</body>');
  115. htmlParts.js.source = getHTMLPart(inlineScriptRE, obj, '<script>${js}</script>');
  116. html = obj.html;
  117. const tm = titleRE.exec(html);
  118. if (tm) {
  119. g.title = tm[1];
  120. }
  121. let scripts = '';
  122. html = html.replace(externalScriptRE, function(p0, p1, p2) {
  123. p1 = p1 || '';
  124. scripts += '\n' + p1 + '<script src="' + p2 + '"></script>';
  125. return '';
  126. });
  127. let dataScripts = '';
  128. html = html.replace(dataScriptRE, function(p0, p1, p2, p3) {
  129. p1 = p1 || '';
  130. dataScripts += '\n' + p1 + '<script ' + p2 + '>' + p3 + '</script>';
  131. return '';
  132. });
  133. htmlParts.html.source += dataScripts;
  134. htmlParts.html.source += scripts + '\n';
  135. // add style section if there is non
  136. if (html.indexOf('${css}') < 0) {
  137. html = html.replace('</head>', '<style>\n${css}</style>\n</head>');
  138. }
  139. // add hackedparams section.
  140. // We need a way to pass parameters to a blob. Normally they'd be passed as
  141. // query params but that only works in Firefox >:(
  142. html = html.replace('</head>', '<script id="hackedparams">window.hackedParams = ${hackedParams}\n</script>\n</head>');
  143. let links = '';
  144. html = html.replace(cssLinkRE, function(p0, p1) {
  145. if (isCSSLinkRE.test(p1)) {
  146. const m = hrefRE.exec(p1);
  147. if (m) {
  148. links += `@import url("${m[1]}");\n`;
  149. }
  150. return '';
  151. } else {
  152. return p0;
  153. }
  154. });
  155. htmlParts.css.source = links + htmlParts.css.source;
  156. g.html = html;
  157. }
  158. function cantGetHTML(e) { // eslint-disable-line
  159. console.log(e); // eslint-disable-line
  160. console.log("TODO: don't run editor if can't get HTML"); // eslint-disable-line
  161. }
  162. function main() {
  163. const query = getQuery();
  164. g.url = getFQUrl(query.url);
  165. g.query = getSearch(g.url);
  166. getHTML(query.url, function(err, html) {
  167. if (err) {
  168. console.log(err); // eslint-disable-line
  169. return;
  170. }
  171. parseHTML(query.url, html);
  172. setupEditor(query.url);
  173. if (query.startPane) {
  174. const button = document.querySelector('.button-' + query.startPane);
  175. toggleSourcePane(button);
  176. }
  177. });
  178. }
  179. let blobUrl;
  180. function getSourceBlob(htmlParts, options) {
  181. options = options || {};
  182. if (blobUrl) {
  183. URL.revokeObjectURL(blobUrl);
  184. }
  185. const prefix = dirname(g.url);
  186. let source = g.html;
  187. source = source.replace('${hackedParams}', JSON.stringify(g.query));
  188. source = source.replace('${html}', htmlParts.html);
  189. source = source.replace('${css}', htmlParts.css);
  190. source = source.replace('${js}', htmlParts.js);
  191. source = source.replace('<head>', '<head>\n<script match="false">threejsLessonSettings = ' + JSON.stringify(options) + ';</script>');
  192. source = source.replace('</head>', '<script src="' + prefix + '/resources/threejs-lessons-helper.js"></script>\n</head>');
  193. const scriptNdx = source.indexOf('<script>');
  194. g.numLinesBeforeScript = (source.substring(0, scriptNdx).match(/\n/g) || []).length;
  195. const blob = new Blob([source], {type: 'text/html'});
  196. blobUrl = URL.createObjectURL(blob);
  197. return blobUrl;
  198. }
  199. function getSourceBlobFromEditor(options) {
  200. return getSourceBlob({
  201. html: htmlParts.html.editor.getValue(),
  202. css: htmlParts.css.editor.getValue(),
  203. js: htmlParts.js.editor.getValue(),
  204. }, options);
  205. }
  206. function getSourceBlobFromOrig(options) {
  207. return getSourceBlob({
  208. html: htmlParts.html.source,
  209. css: htmlParts.css.source,
  210. js: htmlParts.js.source,
  211. }, options);
  212. }
  213. function dirname(path) {
  214. const ndx = path.lastIndexOf('/');
  215. return path.substring(0, ndx + 1);
  216. }
  217. function resize() {
  218. forEachHTMLPart(function(info) {
  219. info.editor.layout();
  220. });
  221. }
  222. function addCORSSupport(js) {
  223. // not yet needed for three.js
  224. return js;
  225. }
  226. function openInCodepen() {
  227. const comment = `// ${g.title}
  228. // from ${g.url}
  229. `;
  230. const pen = {
  231. title : g.title,
  232. description : 'from: ' + g.url,
  233. tags : ['three.js', 'threejsfundamentals.org'],
  234. editors : '101',
  235. html : htmlParts.html.editor.getValue().replace(lessonHelperScriptRE, ''),
  236. css : htmlParts.css.editor.getValue(),
  237. js : comment + addCORSSupport(htmlParts.js.editor.getValue()),
  238. };
  239. const elem = document.createElement('div');
  240. elem.innerHTML = `
  241. <form method="POST" target="_blank" action="https://codepen.io/pen/define" class="hidden">'
  242. <input type="hidden" name="data">
  243. <input type="submit" />
  244. "</form>"
  245. `;
  246. elem.querySelector('input[name=data]').value = JSON.stringify(pen);
  247. window.frameElement.ownerDocument.body.appendChild(elem);
  248. elem.querySelector('form').submit();
  249. window.frameElement.ownerDocument.body.removeChild(elem);
  250. }
  251. function openInJSFiddle() {
  252. const comment = `// ${g.title}
  253. // from ${g.url}
  254. `;
  255. // const pen = {
  256. // title : g.title,
  257. // description : "from: " + g.url,
  258. // tags : ["three.js", "threejsfundamentals.org"],
  259. // editors : "101",
  260. // html : htmlParts.html.editor.getValue(),
  261. // css : htmlParts.css.editor.getValue(),
  262. // js : comment + htmlParts.js.editor.getValue(),
  263. // };
  264. const elem = document.createElement('div');
  265. elem.innerHTML = `
  266. <form method="POST" target="_black" action="https://jsfiddle.net/api/mdn/" class="hidden">
  267. <input type="hidden" name="html" />
  268. <input type="hidden" name="css" />
  269. <input type="hidden" name="js" />
  270. <input type="hidden" name="title" />
  271. <input type="hidden" name="wrap" value="b" />
  272. <input type="submit" />
  273. </form>
  274. `;
  275. elem.querySelector('input[name=html]').value = htmlParts.html.editor.getValue().replace(lessonHelperScriptRE, '');
  276. elem.querySelector('input[name=css]').value = htmlParts.css.editor.getValue();
  277. elem.querySelector('input[name=js]').value = comment + addCORSSupport(htmlParts.js.editor.getValue());
  278. elem.querySelector('input[name=title]').value = g.title;
  279. window.frameElement.ownerDocument.body.appendChild(elem);
  280. elem.querySelector('form').submit();
  281. window.frameElement.ownerDocument.body.removeChild(elem);
  282. }
  283. function setupEditor() {
  284. forEachHTMLPart(function(info, ndx, name) {
  285. info.parent = document.querySelector('.panes>.' + name);
  286. info.editor = runEditor(info.parent, info.source, info.language);
  287. info.button = document.querySelector('.button-' + name);
  288. info.button.addEventListener('click', function() {
  289. toggleSourcePane(info.button);
  290. run();
  291. });
  292. });
  293. g.fullscreen = document.querySelector('.button-fullscreen');
  294. g.fullscreen.addEventListener('click', toggleFullscreen);
  295. g.run = document.querySelector('.button-run');
  296. g.run.addEventListener('click', run);
  297. g.iframe = document.querySelector('.result>iframe');
  298. g.other = document.querySelector('.panes .other');
  299. document.querySelector('.button-codepen').addEventListener('click', openInCodepen);
  300. document.querySelector('.button-jsfiddle').addEventListener('click', openInJSFiddle);
  301. g.result = document.querySelector('.panes .result');
  302. g.resultButton = document.querySelector('.button-result');
  303. g.resultButton.addEventListener('click', function() {
  304. toggleResultPane();
  305. run();
  306. });
  307. g.result.style.display = 'none';
  308. toggleResultPane();
  309. if (window.innerWidth > 1200) {
  310. toggleSourcePane(htmlParts.js.button);
  311. }
  312. window.addEventListener('resize', resize);
  313. showOtherIfAllPanesOff();
  314. document.querySelector('.other .loading').style.display = 'none';
  315. resize();
  316. run({glDebug: false});
  317. }
  318. function toggleFullscreen() {
  319. try {
  320. toggleIFrameFullscreen(window);
  321. resize();
  322. run();
  323. } catch (e) {
  324. console.error(e); // eslint-disable-line
  325. }
  326. }
  327. function run(options) {
  328. g.setPosition = false;
  329. const url = getSourceBlobFromEditor(options);
  330. g.iframe.src = url;
  331. }
  332. function addClass(elem, className) {
  333. const parts = elem.className.split(' ');
  334. if (parts.indexOf(className) < 0) {
  335. elem.className = elem.className + ' ' + className;
  336. }
  337. }
  338. function removeClass(elem, className) {
  339. const parts = elem.className.split(' ');
  340. const numParts = parts.length;
  341. for (;;) {
  342. const ndx = parts.indexOf(className);
  343. if (ndx < 0) {
  344. break;
  345. }
  346. parts.splice(ndx, 1);
  347. }
  348. if (parts.length !== numParts) {
  349. elem.className = parts.join(' ');
  350. return true;
  351. }
  352. return false;
  353. }
  354. function toggleClass(elem, className) {
  355. if (removeClass(elem, className)) {
  356. return false;
  357. } else {
  358. addClass(elem, className);
  359. return true;
  360. }
  361. }
  362. function toggleIFrameFullscreen(childWindow) {
  363. const frame = childWindow.frameElement;
  364. if (frame) {
  365. const isFullScreen = toggleClass(frame, 'fullscreen');
  366. frame.ownerDocument.body.style.overflow = isFullScreen ? 'hidden' : '';
  367. }
  368. }
  369. function addRemoveClass(elem, className, add) {
  370. if (add) {
  371. addClass(elem, className);
  372. } else {
  373. removeClass(elem, className);
  374. }
  375. }
  376. function toggleSourcePane(pressedButton) {
  377. forEachHTMLPart(function(info) {
  378. const pressed = pressedButton === info.button;
  379. if (pressed && !info.showing) {
  380. addClass(info.button, 'show');
  381. info.parent.style.display = 'block';
  382. info.showing = true;
  383. } else {
  384. removeClass(info.button, 'show');
  385. info.parent.style.display = 'none';
  386. info.showing = false;
  387. }
  388. });
  389. showOtherIfAllPanesOff();
  390. resize();
  391. }
  392. function showingResultPane() {
  393. return g.result.style.display !== 'none';
  394. }
  395. function toggleResultPane() {
  396. const showing = showingResultPane();
  397. g.result.style.display = showing ? 'none' : 'block';
  398. addRemoveClass(g.resultButton, 'show', !showing);
  399. showOtherIfAllPanesOff();
  400. resize();
  401. }
  402. function showOtherIfAllPanesOff() {
  403. let paneOn = showingResultPane();
  404. forEachHTMLPart(function(info) {
  405. paneOn = paneOn || info.showing;
  406. });
  407. g.other.style.display = paneOn ? 'none' : 'block';
  408. }
  409. function getActualLineNumberAndMoveTo(lineNo, colNo) {
  410. const actualLineNo = lineNo - g.numLinesBeforeScript;
  411. if (!g.setPosition) {
  412. // Only set the first position
  413. g.setPosition = true;
  414. htmlParts.js.editor.setPosition({
  415. lineNumber: actualLineNo,
  416. column: colNo,
  417. });
  418. htmlParts.js.editor.revealLineInCenterIfOutsideViewport(actualLineNo);
  419. htmlParts.js.editor.focus();
  420. }
  421. return actualLineNo;
  422. }
  423. window.getActualLineNumberAndMoveTo = getActualLineNumberAndMoveTo;
  424. function runEditor(parent, source, language) {
  425. return monaco.editor.create(parent, {
  426. value: source,
  427. language: language,
  428. //lineNumbers: false,
  429. theme: 'vs-dark',
  430. disableTranslate3d: true,
  431. // model: null,
  432. scrollBeyondLastLine: false,
  433. minimap: { enabled: false },
  434. });
  435. }
  436. function runAsBlob() {
  437. const query = getQuery();
  438. g.url = getFQUrl(query.url);
  439. g.query = getSearch(g.url);
  440. getHTML(query.url, function(err, html) {
  441. if (err) {
  442. console.log(err); // eslint-disable-line
  443. return;
  444. }
  445. parseHTML(query.url, html);
  446. window.location.href = getSourceBlobFromOrig();
  447. });
  448. }
  449. function start() {
  450. const parentQuery = getQuery(window.parent.location.search);
  451. const isSmallish = window.navigator.userAgent.match(/Android|iPhone|iPod|Windows Phone/i);
  452. const isEdge = window.navigator.userAgent.match(/Edge/i);
  453. if (isEdge || isSmallish || parentQuery.editor === 'false') {
  454. runAsBlob();
  455. // var url = query.url;
  456. // window.location.href = url;
  457. } else {
  458. require.config({ paths: { 'vs': '/monaco-editor/min/vs' }});
  459. require(['vs/editor/editor.main'], main);
  460. }
  461. }
  462. start();
  463. }());