editor.js 15 KB

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