editor.js 16 KB

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