editor.js 16 KB

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