editor.js 15 KB

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