forked from mrdoob/three.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheditor.js
1458 lines (1283 loc) · 42.6 KB
/
editor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function() { // eslint-disable-line strict
'use strict'; // eslint-disable-line strict
/* global monaco, require, lessonEditorSettings */
const {
fixSourceLinks,
fixJSForCodeSite,
extraHTMLParsing,
runOnResize,
lessonSettings,
} = lessonEditorSettings;
const lessonHelperScriptRE = /<script src="[^"]+lessons-helper\.js"><\/script>/;
const webglDebugHelperScriptRE = /<script src="[^"]+webgl-debug-helper\.js"><\/script>/;
function getQuery(s) {
s = s === undefined ? window.location.search : s;
if (s[0] === '?' ) {
s = s.substring(1);
}
const query = {};
s.split('&').forEach(function(pair) {
const parts = pair.split('=').map(decodeURIComponent);
query[parts[0]] = parts[1];
});
return query;
}
function getSearch(url) {
// yea I know this is not perfect but whatever
const s = url.indexOf('?');
return s < 0 ? {} : getQuery(url.substring(s));
}
function getFQUrl(path, baseUrl) {
const url = new URL(path, baseUrl || window.location.href);
return url.href;
}
async function getHTML(url) {
const req = await fetch(url);
return await req.text();
}
function getPrefix(url) {
const u = new URL(url, window.location.href);
const prefix = u.origin + dirname(u.pathname);
return prefix;
}
function fixCSSLinks(url, source) {
const cssUrlRE1 = /(url\(')(.*?)('\))/g;
const cssUrlRE2 = /(url\()(.*?)(\))/g;
const prefix = getPrefix(url);
function addPrefix(url) {
return url.indexOf('://') < 0 && !url.startsWith('data:') ? `${prefix}/${url}` : url;
}
function makeFQ(match, prefix, url, suffix) {
return `${prefix}${addPrefix(url)}${suffix}`;
}
source = source.replace(cssUrlRE1, makeFQ);
source = source.replace(cssUrlRE2, makeFQ);
return source;
}
/**
* @typedef {Object} Globals
* @property {SourceInfo} rootScriptInfo
* @property {Object<string, SourceInfo} scriptInfos
*/
/** @type {Globals} */
const g = {
html: '',
};
/**
* This is what's in the sources array
* @typedef {Object} SourceInfo
* @property {string} source The source text (html, css, js)
* @property {string} name The filename or "main page"
* @property {ScriptInfo} scriptInfo The associated ScriptInfo
* @property {string} fqURL ??
* @property {Editor} editor in instance of Monaco editor
*
*/
/**
* @typedef {Object} EditorInfo
* @property {HTMLElement} div The div holding the monaco editor
* @property {Editor} editor an instance of a monaco editor
*/
/**
* What's under each language
* @typedef {Object} HTMLPart
* @property {string} language Name of language
* @property {SourceInfo} sources array of SourceInfos. Usually 1 for HTML, 1 for CSS, N for JS
* @property {HTMLElement} pane the pane for these editors
* @property {HTMLElement} code the div holding the files
* @property {HTMLElement} files the div holding the divs holding the monaco editors
* @property {HTMLElement} button the element to click to show this pane
* @property {EditorInfo} editors
*/
/** @type {Object<string, HTMLPart>} */
const htmlParts = {
js: {
language: 'javascript',
sources: [],
},
css: {
language: 'css',
sources: [],
},
html: {
language: 'html',
sources: [],
},
};
function forEachHTMLPart(fn) {
Object.keys(htmlParts).forEach(function(name, ndx) {
const info = htmlParts[name];
fn(info, ndx, name);
});
}
function getHTMLPart(re, obj, tag) {
let part = '';
obj.html = obj.html.replace(re, function(p0, p1) {
part = p1;
return tag;
});
return part.replace(/\s*/, '');
}
// doesn't handle multi-line comments or comments with { or } in them
function formatCSS(css) {
let indent = '';
return css.split('\n').map((line) => {
let currIndent = indent;
if (line.includes('{')) {
indent = indent + ' ';
} else if (line.includes('}')) {
indent = indent.substring(0, indent.length - 2);
currIndent = indent;
}
return `${currIndent}${line.trim()}`;
}).join('\n');
}
async function getScript(url, scriptInfos) {
// check it's an example script, not some other lib
if (!scriptInfos[url].source) {
const source = await getHTML(url);
const fixedSource = fixSourceLinks(url, source);
const {text} = await getWorkerScripts(fixedSource, url, scriptInfos);
scriptInfos[url].source = text;
}
}
/**
* @typedef {Object} ScriptInfo
* @property {string} fqURL The original fully qualified URL
* @property {ScriptInfo[]} deps Array of other ScriptInfos this is script dependant on
* @property {boolean} isWorker True if this script came from `new Worker('someurl')` vs `import` or `importScripts`
* @property {string} blobUrl The blobUrl for this script if one has been made
* @property {number} blobGenerationId Used to not visit things twice while recursing.
* @property {string} source The source as extracted. Updated from editor by getSourcesFromEditor
* @property {string} munged The source after urls have been replaced with blob urls etc... (the text send to new Blob)
*/
async function getWorkerScripts(text, baseUrl, scriptInfos = {}) {
const parentScriptInfo = scriptInfos[baseUrl];
const workerRE = /(new\s+Worker\s*\(\s*)('|")(.*?)('|")/g;
const importScriptsRE = /(importScripts\s*\(\s*)('|")(.*?)('|")/g;
const importRE = /(import.*?)('|")(.*?)('|")/g;
const newScripts = [];
const slashRE = /\/manual\/examples\/[^/]+$/;
function replaceWithUUID(match, prefix, quote, url) {
const fqURL = getFQUrl(url, baseUrl);
if (!slashRE.test(fqURL)) {
return match.toString();
}
if (!scriptInfos[url]) {
scriptInfos[fqURL] = {
fqURL,
deps: [],
isWorker: prefix.indexOf('Worker') >= 0,
};
newScripts.push(fqURL);
}
parentScriptInfo.deps.push(scriptInfos[fqURL]);
return `${prefix}${quote}${fqURL}${quote}`;
}
text = text.replace(workerRE, replaceWithUUID);
text = text.replace(importScriptsRE, replaceWithUUID);
text = text.replace(importRE, replaceWithUUID);
await Promise.all(newScripts.map((url) => {
return getScript(url, scriptInfos);
}));
return {text, scriptInfos};
}
// hack: scriptInfo is undefined for html and css
// should try to include html and css in scriptInfos
function addSource(type, name, source, scriptInfo) {
htmlParts[type].sources.push({source, name, scriptInfo});
}
function safeStr(s) {
return s === undefined ? '' : s;
}
async function parseHTML(url, html) {
html = fixSourceLinks(url, html);
html = html.replace(/<div class="description">[^]*?<\/div>/, '');
const styleRE = /<style>([^]*?)<\/style>/i;
const titleRE = /<title>([^]*?)<\/title>/i;
const bodyRE = /<body>([^]*?)<\/body>/i;
const inlineScriptRE = /<script>([^]*?)<\/script>/i;
const inlineModuleScriptRE = /<script type="module">([^]*?)<\/script>/i;
const externalScriptRE = /(<!--(?:(?!-->)[\s\S])*?-->\n){0,1}<script\s+(type="module"\s+)?src\s*=\s*"(.*?)"\s*>\s*<\/script>/ig;
const dataScriptRE = /(<!--(?:(?!-->)[\s\S])*?-->\n){0,1}<script(.*?id=".*?)>([^]*?)<\/script>/ig;
const cssLinkRE = /<link ([^>]+?)>/g;
const isCSSLinkRE = /type="text\/css"|rel="stylesheet"/;
const hrefRE = /href="([^"]+)"/;
const obj = { html: html };
addSource('css', 'css', formatCSS(fixCSSLinks(url, getHTMLPart(styleRE, obj, '<style>\n${css}</style>'))));
addSource('html', 'html', getHTMLPart(bodyRE, obj, '<body>${html}</body>'));
const rootScript = getHTMLPart(inlineScriptRE, obj, '<script>${js}</script>') ||
getHTMLPart(inlineModuleScriptRE, obj, '<script type="module">${js}</script>');
html = obj.html;
const fqURL = getFQUrl(url);
/** @type Object<string, SourceInfo> */
const scriptInfos = {};
g.rootScriptInfo = {
fqURL,
deps: [],
source: rootScript,
};
scriptInfos[fqURL] = g.rootScriptInfo;
const {text} = await getWorkerScripts(rootScript, fqURL, scriptInfos);
g.rootScriptInfo.source = text;
g.scriptInfos = scriptInfos;
for (const [fqURL, scriptInfo] of Object.entries(scriptInfos)) {
addSource('js', basename(fqURL), scriptInfo.source, scriptInfo);
}
const tm = titleRE.exec(html);
if (tm) {
g.title = tm[1];
}
const kScript = 'script';
const scripts = [];
html = html.replace(externalScriptRE, function(p0, p1, type, p2) {
p1 = p1 || '';
scripts.push(`${p1}<${kScript} ${safeStr(type)}src="${p2}"></${kScript}>`);
return '';
});
const dataScripts = [];
html = html.replace(dataScriptRE, function(p0, p1, p2, p3) {
p1 = p1 || '';
dataScripts.push(`${p1}<${kScript} ${p2}>${p3}</${kScript}>`);
return '';
});
htmlParts.html.sources[0].source += dataScripts.join('\n');
htmlParts.html.sources[0].source += scripts.join('\n');
// add style section if there is non
if (html.indexOf('${css}') < 0) {
html = html.replace('</head>', '<style>\n${css}</style>\n</head>');
}
// add hackedparams section.
// We need a way to pass parameters to a blob. Normally they'd be passed as
// query params but that only works in Firefox >:(
html = html.replace('</head>', '<script id="hackedparams">window.hackedParams = ${hackedParams}\n</script>\n</head>');
html = extraHTMLParsing(html, htmlParts);
let links = '';
html = html.replace(cssLinkRE, function(p0, p1) {
if (isCSSLinkRE.test(p1)) {
const m = hrefRE.exec(p1);
if (m) {
links += `@import url("${m[1]}");\n`;
}
return '';
} else {
return p0;
}
});
htmlParts.css.sources[0].source = links + htmlParts.css.sources[0].source;
g.html = html;
}
async function main() {
const query = getQuery();
g.url = getFQUrl(query.url);
g.query = getSearch(g.url);
let html;
try {
html = await getHTML(query.url);
} catch (err) {
console.log(err); // eslint-disable-line
return;
}
await parseHTML(query.url, html);
setupEditor();
if (query.startPane) {
const button = document.querySelector('.button-' + query.startPane);
toggleSourcePane(button);
}
}
function getJavaScriptBlob(source) {
const blob = new Blob([source], {type: 'application/javascript'});
return URL.createObjectURL(blob);
}
let blobGeneration = 0;
function makeBlobURLsForSources(scriptInfo) {
++blobGeneration;
function makeBlobURLForSourcesImpl(scriptInfo) {
if (scriptInfo.blobGenerationId !== blobGeneration) {
scriptInfo.blobGenerationId = blobGeneration;
if (scriptInfo.blobUrl) {
URL.revokeObjectURL(scriptInfo.blobUrl);
}
scriptInfo.deps.forEach(makeBlobURLForSourcesImpl);
let text = scriptInfo.source;
scriptInfo.deps.forEach((depScriptInfo) => {
text = text.split(depScriptInfo.fqURL).join(depScriptInfo.blobUrl);
});
scriptInfo.numLinesBeforeScript = 0;
if (scriptInfo.isWorker) {
const extra = `self.lessonSettings = ${JSON.stringify(lessonSettings)};
import '${dirname(scriptInfo.fqURL)}/resources/webgl-debug-helper.js';
import '${dirname(scriptInfo.fqURL)}/resources/lessons-worker-helper.js';`;
scriptInfo.numLinesBeforeScript = extra.split('\n').length;
text = `${extra}\n${text}`;
}
scriptInfo.blobUrl = getJavaScriptBlob(text);
scriptInfo.munged = text;
}
}
makeBlobURLForSourcesImpl(scriptInfo);
}
function getSourceBlob(htmlParts) {
g.rootScriptInfo.source = htmlParts.js;
makeBlobURLsForSources(g.rootScriptInfo);
const dname = dirname(g.url);
// HACK! for webgl-2d-vs... those examples are not in /webgl they're in /webgl/resources
// We basically assume url is https://foo/base/example.html so there will be 4 slashes
// If the path is longer than then we need '../' to back up so prefix works below
const prefix = dname; //`${dname}${dname.split('/').slice(4).map(() => '/..').join('')}`;
let source = g.html;
source = source.replace('${hackedParams}', JSON.stringify(g.query));
source = source.replace('${html}', htmlParts.html);
source = source.replace('${css}', htmlParts.css);
source = source.replace('${js}', g.rootScriptInfo.munged); //htmlParts.js);
source = source.replace('<head>', `<head>
<link rel="stylesheet" href="${prefix}/resources/lesson-helper.css" type="text/css">
<script match="false">self.lessonSettings = ${JSON.stringify(lessonSettings)}</script>`);
source = source.replace('</head>', `
<script async src="https://ga.jspm.io/npm:es-module-shims@1.4.3/dist/es-module-shims.js"></script>
<script type='importmap-shim'>
{
"imports": {
"three": "${location.href.slice(0, location.href.indexOf('/manual/'))}/build/three.module.js"
}
}
</script>
<script src="${prefix}/resources/webgl-debug-helper.js"></script>
<script src="${prefix}/resources/lessons-helper.js"></script>
</head>`);
const scriptNdx = source.search(/<script(\s+type="module"\s*)?>/);
g.rootScriptInfo.numLinesBeforeScript = (source.substring(0, scriptNdx).match(/\n/g) || []).length;
source = source.replace(/type=['"]module['"]/, 'type="module-shim"');
return source;
// const blob = new Blob([source], {type: 'text/html'});
// // This seems hacky. We are combining html/css/js into one html blob but we already made
// // a blob for the JS so let's replace that blob. That means it will get auto-released when script blobs
// // are regenerated. It also means error reporting will work
// const blobUrl = URL.createObjectURL(blob);
// URL.revokeObjectURL(g.rootScriptInfo.blobUrl);
// g.rootScriptInfo.blobUrl = blobUrl;
// return blobUrl;
}
function getSourcesFromEditor() {
for (const partTypeInfo of Object.values(htmlParts)) {
for (const source of partTypeInfo.sources) {
source.source = source.editor.getValue();
// hack: shouldn't store this twice. Also see other comment,
// should consolidate so scriptInfo is used for css and html
if (source.scriptInfo) {
source.scriptInfo.source = source.source;
}
}
}
}
function getSourceBlobFromEditor() {
getSourcesFromEditor();
return getSourceBlob({
html: htmlParts.html.sources[0].source,
css: htmlParts.css.sources[0].source,
js: htmlParts.js.sources[0].source,
});
}
function getSourceBlobFromOrig() {
return getSourceBlob({
html: htmlParts.html.sources[0].source,
css: htmlParts.css.sources[0].source,
js: htmlParts.js.sources[0].source,
});
}
function dirname(path) {
const ndx = path.lastIndexOf('/');
return path.substring(0, ndx);
}
function basename(path) {
const ndx = path.lastIndexOf('/');
return path.substring(ndx + 1);
}
function resize() {
forEachHTMLPart(function(info) {
info.editors.forEach((editorInfo) => {
editorInfo.editor.layout();
});
});
}
function getScripts(scriptInfo) {
++blobGeneration;
function getScriptsImpl(scriptInfo) {
const scripts = [];
if (scriptInfo.blobGenerationId !== blobGeneration) {
scriptInfo.blobGenerationId = blobGeneration;
scripts.push(...scriptInfo.deps.map(getScriptsImpl).flat());
let text = scriptInfo.source;
scriptInfo.deps.forEach((depScriptInfo) => {
text = text.split(depScriptInfo.fqURL).join(`worker-${basename(depScriptInfo.fqURL)}`);
});
scripts.push({
name: `worker-${basename(scriptInfo.fqURL)}`,
text,
});
}
return scripts;
}
return getScriptsImpl(scriptInfo);
}
function makeScriptsForWorkers(scriptInfo) {
const scripts = getScripts(scriptInfo);
if (scripts.length === 1) {
return {
js: scripts[0].text,
html: '',
};
}
// scripts[last] = main script
// scripts[last - 1] = worker
const mainScriptInfo = scripts[scripts.length - 1];
const workerScriptInfo = scripts[scripts.length - 2];
const workerName = workerScriptInfo.name;
mainScriptInfo.text = mainScriptInfo.text.split(`'${workerName}'`).join('getWorkerBlob()');
const html = scripts.map((nameText) => {
const {name, text} = nameText;
return `<script id="${name}" type="x-worker">\n${text}\n</script>\n`;
}).join('\n');
const init = `
// ------
// Creates Blobs for the Scripts so things can be self contained for snippets/JSFiddle/Codepen
// even though they are using workers
//
(function() {
const idsToUrls = [];
const scriptElements = [...document.querySelectorAll('script[type=x-worker]')];
for (const scriptElement of scriptElements) {
let text = scriptElement.text;
for (const {id, url} of idsToUrls) {
text = text.split(id).join(url);
}
const blob = new Blob([text], {type: 'application/javascript'});
const url = URL.createObjectURL(blob);
const id = scriptElement.id;
idsToUrls.push({id, url});
}
window.getWorkerBlob = function() {
return idsToUrls.pop().url;
};
import(window.getWorkerBlob());
}());
`;
return {
js: init,
html,
};
}
async function fixHTMLForCodeSite(html) {
html = html.replace(lessonHelperScriptRE, '');
html = html.replace(webglDebugHelperScriptRE, '');
return html;
}
async function openInCodepen() {
const comment = `// ${g.title}
// from ${g.url}
`;
getSourcesFromEditor();
const scripts = makeScriptsForWorkers(g.rootScriptInfo);
const code = await fixJSForCodeSite(scripts.js);
const html = await fixHTMLForCodeSite(htmlParts.html.sources[0].source);
const pen = {
title : g.title,
description : 'from: ' + g.url,
tags : lessonEditorSettings.tags,
editors : '101',
html : scripts.html + html,
css : htmlParts.css.sources[0].source,
js : comment + code,
};
const elem = document.createElement('div');
elem.innerHTML = `
<form method="POST" target="_blank" action="https://codepen.io/pen/define" class="hidden">'
<input type="hidden" name="data">
<input type="submit" />
"</form>"
`;
elem.querySelector('input[name=data]').value = JSON.stringify(pen);
window.frameElement.ownerDocument.body.appendChild(elem);
elem.querySelector('form').submit();
window.frameElement.ownerDocument.body.removeChild(elem);
}
async function openInJSFiddle() {
const comment = `// ${g.title}
// from ${g.url}
`;
getSourcesFromEditor();
const scripts = makeScriptsForWorkers(g.rootScriptInfo);
const code = await fixJSForCodeSite(scripts.js);
const html = await fixHTMLForCodeSite(htmlParts.html.sources[0].source);
const elem = document.createElement('div');
elem.innerHTML = `
<form method="POST" target="_black" action="https://jsfiddle.net/api/mdn/" class="hidden">
<input type="hidden" name="html" />
<input type="hidden" name="css" />
<input type="hidden" name="js" />
<input type="hidden" name="title" />
<input type="hidden" name="wrap" value="b" />
<input type="submit" />
</form>
`;
elem.querySelector('input[name=html]').value = scripts.html + html;
elem.querySelector('input[name=css]').value = htmlParts.css.sources[0].source;
elem.querySelector('input[name=js]').value = comment + code;
elem.querySelector('input[name=title]').value = g.title;
window.frameElement.ownerDocument.body.appendChild(elem);
elem.querySelector('form').submit();
window.frameElement.ownerDocument.body.removeChild(elem);
}
async function openInJSGist() {
const comment = `// ${g.title}
// from ${g.url}
`;
getSourcesFromEditor();
const scripts = makeScriptsForWorkers(g.rootScriptInfo);
const code = await fixJSForCodeSite(scripts.js);
const html = await fixHTMLForCodeSite(htmlParts.html.sources[0].source);
const gist = {
name: g.title,
settings: {},
files: [
{ name: 'index.html', content: scripts.html + html, },
{ name: 'index.css', content: htmlParts.css.sources[0].source, },
{ name: 'index.js', content: comment + code, },
],
};
window.open('https://jsgist.org/?newGist=true', '_blank');
const send = (e) => {
e.source.postMessage({type: 'newGist', data: gist}, '*');
};
window.addEventListener('message', send, {once: true});
}
/*
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
console.log();
<!-- language: lang-css -->
h1 { color: red; }
<!-- language: lang-html -->
<h1>foo</h1>
<!-- end snippet -->
*/
function indent4(s) {
return s.split('\n').map(s => ` ${s}`).join('\n');
}
async function openInStackOverflow() {
const comment = `// ${g.title}
// from ${g.url}
`;
getSourcesFromEditor();
const scripts = makeScriptsForWorkers(g.rootScriptInfo);
const code = await fixJSForCodeSite(scripts.js);
const html = await fixHTMLForCodeSite(htmlParts.html.sources[0].source);
const mainHTML = scripts.html + html;
const mainJS = comment + code;
const mainCSS = htmlParts.css.sources[0].source;
const asModule = /\bimport\b/.test(mainJS);
// Three.js wants us to use modules but Stack Overflow doesn't support them
const text = asModule
? `
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
<!-- language: lang-css -->
${indent4(mainCSS)}
<!-- language: lang-html -->
${indent4(mainHTML)}
<script type="module">
${indent4(mainJS)}
</script>
<!-- end snippet -->
`
: `
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
${indent4(mainJS)}
<!-- language: lang-css -->
${indent4(mainCSS)}
<!-- language: lang-html -->
${indent4(mainHTML)}
<!-- end snippet -->
`;
const dialogElem = document.querySelector('.copy-dialog');
dialogElem.style.display = '';
const copyAreaElem = dialogElem.querySelector('.copy-area');
copyAreaElem.textContent = text;
const linkElem = dialogElem.querySelector('a');
const tags = lessonEditorSettings.tags.filter(f => !f.endsWith('.org')).join(' ');
linkElem.href = `https://stackoverflow.com/questions/ask?&tags=javascript ${tags}`;
}
function htmlTemplate(s) {
return `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title>${s.title}</title>
<style>
${s.css}
</style>
</head>
<body>
${s.body}
</body>
${s.script.startsWith('<')
? s.script
: `
<script type="module-shim">
${s.script}
</script>
`}
</html>`;
}
// ---vvv---
// Copyright (c) 2013 Pieroxy <pieroxy@pieroxy.net>
// This work is free. You can redistribute it and/or modify it
// under the terms of the WTFPL, Version 2
// For more information see LICENSE.txt or http://www.wtfpl.net/
//
// For more information, the home page:
// http://pieroxy.net/blog/pages/lz-string/testing.html
//
// LZ-based compression algorithm, version 1.4.4
//
// Modified:
// private property
const keyStrBase64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
function compressToBase64(input) {
if (input === null) {
return '';
}
const res = _compress(input, 6, function(a) {
return keyStrBase64.charAt(a);
});
switch (res.length % 4) { // To produce valid Base64
default: // When could this happen ?
case 0 : return res;
case 1 : return res + '===';
case 2 : return res + '==';
case 3 : return res + '=';
}
}
function _compress(uncompressed, bitsPerChar, getCharFromInt) {
let i;
let value;
const context_dictionary = {};
const context_dictionaryToCreate = {};
let context_c = '';
let context_wc = '';
let context_w = '';
let context_enlargeIn = 2; // Compensate for the first entry which should not count
let context_dictSize = 3;
let context_numBits = 2;
const context_data = [];
let context_data_val = 0;
let context_data_position = 0;
let ii;
for (ii = 0; ii < uncompressed.length; ii += 1) {
context_c = uncompressed.charAt(ii);
if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
context_dictionary[context_c] = context_dictSize++;
context_dictionaryToCreate[context_c] = true;
}
context_wc = context_w + context_c;
if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) {
context_w = context_wc;
} else {
if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
if (context_w.charCodeAt(0) < 256) {
for (i = 0; i < context_numBits; i++) {
context_data_val = (context_data_val << 1);
if (context_data_position === bitsPerChar - 1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
}
value = context_w.charCodeAt(0);
for (i = 0; i < 8; i++) {
context_data_val = (context_data_val << 1) | (value & 1);
if (context_data_position === bitsPerChar - 1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
} else {
value = 1;
for (i = 0; i < context_numBits; i++) {
context_data_val = (context_data_val << 1) | value;
if (context_data_position === bitsPerChar - 1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
value = 0;
}
value = context_w.charCodeAt(0);
for (i = 0; i < 16; i++) {
context_data_val = (context_data_val << 1) | (value & 1);
if (context_data_position === bitsPerChar - 1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
}
context_enlargeIn--;
if (context_enlargeIn === 0) {
context_enlargeIn = Math.pow(2, context_numBits);
context_numBits++;
}
delete context_dictionaryToCreate[context_w];
} else {
value = context_dictionary[context_w];
for (i = 0; i < context_numBits; i++) {
context_data_val = (context_data_val << 1) | (value & 1);
if (context_data_position === bitsPerChar - 1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
}
context_enlargeIn--;
if (context_enlargeIn === 0) {
context_enlargeIn = Math.pow(2, context_numBits);
context_numBits++;
}
// Add wc to the dictionary.
context_dictionary[context_wc] = context_dictSize++;
context_w = String(context_c);
}
}
// Output the code for w.
if (context_w !== '') {
if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
if (context_w.charCodeAt(0) < 256) {
for (i = 0; i < context_numBits; i++) {
context_data_val = (context_data_val << 1);
if (context_data_position === bitsPerChar - 1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
}
value = context_w.charCodeAt(0);
for (i = 0; i < 8; i++) {
context_data_val = (context_data_val << 1) | (value & 1);
if (context_data_position === bitsPerChar - 1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
} else {
value = 1;
for (i = 0; i < context_numBits; i++) {
context_data_val = (context_data_val << 1) | value;
if (context_data_position === bitsPerChar - 1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
value = 0;
}
value = context_w.charCodeAt(0);
for (i = 0; i < 16; i++) {
context_data_val = (context_data_val << 1) | (value & 1);
if (context_data_position === bitsPerChar - 1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
}
context_enlargeIn--;
if (context_enlargeIn === 0) {
context_enlargeIn = Math.pow(2, context_numBits);
context_numBits++;
}
delete context_dictionaryToCreate[context_w];
} else {
value = context_dictionary[context_w];
for (i = 0; i < context_numBits; i++) {
context_data_val = (context_data_val << 1) | (value & 1);
if (context_data_position === bitsPerChar - 1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
}
context_enlargeIn--;
if (context_enlargeIn === 0) {
context_numBits++;
}
}
// Mark the end of the stream
value = 2;
for (i = 0; i < context_numBits; i++) {
context_data_val = (context_data_val << 1) | (value & 1);
if (context_data_position === bitsPerChar - 1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
// Flush the last char
for (;;) {
context_data_val = (context_data_val << 1);
if (context_data_position === bitsPerChar - 1) {
context_data.push(getCharFromInt(context_data_val));
break;
} else {
context_data_position++;
}
}
return context_data.join('');
}
function compress(input) {
return compressToBase64(input)
.replace(/\+/g, '-') // Convert '+' to '-'