forked from microsoft/pxt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunner.ts
1219 lines (1074 loc) · 45.1 KB
/
runner.ts
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
/* TODO(tslint): get rid of jquery html() calls */
/// <reference path="../built/pxtlib.d.ts" />
/// <reference path="../built/pxteditor.d.ts" />
/// <reference path="../built/pxtcompiler.d.ts" />
/// <reference path="../built/pxtblocks.d.ts" />
/// <reference path="../built/pxtsim.d.ts" />
namespace pxt.runner {
export interface SimulateOptions {
id?: string;
code?: string;
assets?: string;
highContrast?: boolean;
light?: boolean;
fullScreen?: boolean;
dependencies?: string[];
builtJsInfo?: pxtc.BuiltSimJsInfo;
// single simulator frame, no message simulators
single?: boolean;
}
class EditorPackage {
files: Map<string> = {};
id: string;
constructor(private ksPkg: pxt.Package, public topPkg: EditorPackage) {
}
getKsPkg() {
return this.ksPkg;
}
getPkgId() {
return this.ksPkg ? this.ksPkg.id : this.id;
}
isTopLevel() {
return this.ksPkg && this.ksPkg.level == 0;
}
setFiles(files: Map<string>) {
this.files = files;
}
getAllFiles() {
return Util.mapMap(this.files, (k, f) => f)
}
}
class Host
implements pxt.Host {
readFile(module: pxt.Package, filename: string): string {
let epkg = getEditorPkg(module)
return U.lookup(epkg.files, filename)
}
writeFile(module: pxt.Package, filename: string, contents: string): void {
const epkg = getEditorPkg(module);
epkg.files[filename] = contents;
}
getHexInfoAsync(extInfo: pxtc.ExtensionInfo): Promise<pxtc.HexInfo> {
return pxt.hexloader.getHexInfoAsync(this, extInfo)
}
cacheStoreAsync(id: string, val: string): Promise<void> {
return Promise.resolve()
}
cacheGetAsync(id: string): Promise<string> {
return Promise.resolve(null as string)
}
patchDependencies(cfg: pxt.PackageConfig, name: string, repoId: string): boolean {
if (!repoId) return false;
// check that the same package hasn't been added yet
const repo = pxt.github.parseRepoId(repoId);
if (!repo) return false;
for (const k of Object.keys(cfg.dependencies)) {
const v = cfg.dependencies[k];
const kv = pxt.github.parseRepoId(v);
if (kv && repo.fullName == kv.fullName) {
if (pxt.semver.strcmp(repo.tag, kv.tag) < 0) {
// we have a later tag, use this one
cfg.dependencies[k] = repoId;
}
return true;
}
}
return false;
}
private githubPackageCache: pxt.Map<Map<string>> = {};
downloadPackageAsync(pkg: pxt.Package, dependencies?: string[]) {
let proto = pkg.verProtocol()
let cached: pxt.Map<string> = undefined;
// cache resolve github packages
if (proto == "github")
cached = this.githubPackageCache[pkg._verspec];
let epkg = getEditorPkg(pkg)
return (cached ? Promise.resolve(cached) : pkg.commonDownloadAsync())
.then(resp => {
if (resp) {
if (proto == "github" && !cached)
this.githubPackageCache[pkg._verspec] = Util.clone(resp);
epkg.setFiles(resp)
return Promise.resolve()
}
if (proto == "empty") {
if (Object.keys(epkg.files).length == 0) {
epkg.setFiles(emptyPrjFiles())
}
if (dependencies && dependencies.length) {
const files = getEditorPkg(pkg).files;
const cfg = JSON.parse(files[pxt.CONFIG_NAME]) as pxt.PackageConfig;
dependencies.forEach((d: string) => {
addPackageToConfig(cfg, d);
});
files[pxt.CONFIG_NAME] = pxt.Package.stringifyConfig(cfg);
}
return Promise.resolve()
} else if (proto == "docs") {
let files = emptyPrjFiles();
let cfg = JSON.parse(files[pxt.CONFIG_NAME]) as pxt.PackageConfig;
// load all dependencies
pkg.verArgument().split(',').forEach(d => {
if (!addPackageToConfig(cfg, d)) {
return;
}
});
if (!cfg.yotta) cfg.yotta = {};
cfg.yotta.ignoreConflicts = true;
files[pxt.CONFIG_NAME] = pxt.Package.stringifyConfig(cfg);
epkg.setFiles(files);
return Promise.resolve();
} else if (proto == "invalid") {
pxt.log(`skipping invalid pkg ${pkg.id}`);
return Promise.resolve();
} else {
return Promise.reject(`Cannot download ${pkg.version()}; unknown protocol`)
}
})
}
}
export let mainPkg: pxt.MainPackage;
let tilemapProject: TilemapProject;
if (!pxt.react.getTilemapProject) {
pxt.react.getTilemapProject = () => {
if (!tilemapProject) {
tilemapProject = new TilemapProject();
tilemapProject.loadPackage(mainPkg);
}
return tilemapProject;
}
}
function addPackageToConfig(cfg: pxt.PackageConfig, dep: string) {
let m = /^([a-zA-Z0-9_-]+)(=(.+))?$/.exec(dep);
if (m) {
if (m[3] && this && this.patchDependencies(cfg, m[1], m[3]))
return false;
cfg.dependencies[m[1]] = m[3] || "*"
} else
console.warn(`unknown package syntax ${dep}`)
return true;
}
function getEditorPkg(p: pxt.Package) {
let r: EditorPackage = (p as any)._editorPkg
if (r) return r
let top: EditorPackage = null
if (p != mainPkg)
top = getEditorPkg(mainPkg)
let newOne = new EditorPackage(p, top)
if (p == mainPkg)
newOne.topPkg = newOne;
(p as any)._editorPkg = newOne
return newOne
}
function emptyPrjFiles() {
let p = appTarget.tsprj
let files = U.clone(p.files)
files[pxt.CONFIG_NAME] = pxt.Package.stringifyConfig(p.config);
files["main.blocks"] = "";
return files
}
function patchSemantic() {
if ($ && $.fn && ($.fn as any).embed && ($.fn as any).embed.settings && ($.fn as any).embed.settings.sources && ($.fn as any).embed.settings.sources.youtube) {
($.fn as any).embed.settings.sources.youtube.url = '//www.youtube.com/embed/{id}?rel=0'
}
}
function initInnerAsync() {
pxt.setAppTarget((window as any).pxtTargetBundle)
Util.assert(!!pxt.appTarget);
const href = window.location.href;
let force = false;
let lang: string = undefined;
if (/[&?]translate=1/.test(href) && !pxt.BrowserUtils.isIE()) {
lang = ts.pxtc.Util.TRANSLATION_LOCALE;
force = true;
pxt.Util.enableLiveLocalizationUpdates();
} else {
const cookieValue = /PXT_LANG=(.*?)(?:;|$)/.exec(document.cookie);
const mlang = /(live)?(force)?lang=([a-z]{2,}(-[A-Z]+)?)/i.exec(href);
lang = mlang ? mlang[3] : (cookieValue && cookieValue[1] || pxt.appTarget.appTheme.defaultLocale || (navigator as any).userLanguage || navigator.language);
const liveTranslationsDisabled = pxt.BrowserUtils.isPxtElectron() || pxt.BrowserUtils.isLocalHostDev() || pxt.appTarget.appTheme.disableLiveTranslations;
if (!liveTranslationsDisabled || !!mlang?.[1]) {
pxt.Util.enableLiveLocalizationUpdates();
}
force = !!mlang && !!mlang[2];
}
const versions = pxt.appTarget.versions;
patchSemantic();
const cfg = pxt.webConfig
return Util.updateLocalizationAsync({
targetId: pxt.appTarget.id,
baseUrl: cfg.commitCdnUrl,
code: lang,
pxtBranch: versions ? versions.pxtCrowdinBranch : "",
targetBranch: versions ? versions.targetCrowdinBranch : "",
force: force,
})
.then(() => {
mainPkg = new pxt.MainPackage(new Host());
})
}
export function initFooter(footer: HTMLElement, shareId?: string) {
if (!footer) return;
let theme = pxt.appTarget.appTheme;
let body = $('body');
let $footer = $(footer)
let footera = $('<a/>').attr('href', theme.homeUrl)
.attr('target', '_blank');
$footer.append(footera);
if (theme.organizationLogo)
footera.append($('<img/>').attr('src', Util.toDataUri(theme.organizationLogo)));
else footera.append(lf("powered by {0}", theme.title));
body.mouseenter(ev => $footer.fadeOut());
body.mouseleave(ev => $footer.fadeIn());
}
export function showError(msg: string) {
console.error(msg)
}
let previousMainPackage: pxt.MainPackage = undefined;
function loadPackageAsync(id: string, code?: string, dependencies?: string[]) {
const verspec = id ? /\w+:\w+/.test(id) ? id : "pub:" + id : "empty:tsprj";
let host: pxt.Host;
let downloadPackagePromise: Promise<void>;
let installPromise: Promise<void>;
if (previousMainPackage && previousMainPackage._verspec == verspec) {
mainPkg = previousMainPackage;
host = mainPkg.host();
downloadPackagePromise = Promise.resolve();
installPromise = Promise.resolve();
} else {
host = mainPkg.host();
mainPkg = new pxt.MainPackage(host)
mainPkg._verspec = id ? /\w+:\w+/.test(id) ? id : "pub:" + id : "empty:tsprj"
downloadPackagePromise = host.downloadPackageAsync(mainPkg, dependencies);
installPromise = mainPkg.installAllAsync()
// cache previous package
previousMainPackage = mainPkg;
}
return downloadPackagePromise
.then(() => host.readFile(mainPkg, pxt.CONFIG_NAME))
.then(str => {
if (!str) return Promise.resolve()
return installPromise.then(() => {
if (code) {
//Set the custom code if provided for docs.
let epkg = getEditorPkg(mainPkg);
epkg.files["main.ts"] = code;
//set the custom doc name from the URL.
let cfg = JSON.parse(epkg.files[pxt.CONFIG_NAME]) as pxt.PackageConfig;
cfg.name = window.location.href.split('/').pop().split(/[?#]/)[0];;
epkg.files[pxt.CONFIG_NAME] = pxt.Package.stringifyConfig(cfg);
//Propgate the change to main package
mainPkg.config.name = cfg.name;
if (mainPkg.config.files.indexOf("main.blocks") == -1) {
mainPkg.config.files.push("main.blocks");
}
}
}).catch(e => {
showError(lf("Cannot load extension: {0}", e.message))
})
});
}
function getCompileOptionsAsync(hex?: boolean) {
let trg = mainPkg.getTargetOptions()
trg.isNative = !!hex
trg.hasHex = !!hex
return mainPkg.getCompileOptionsAsync(trg)
}
function compileAsync(hex: boolean, updateOptions?: (ops: pxtc.CompileOptions) => void) {
return getCompileOptionsAsync(hex)
.then(opts => {
if (updateOptions) updateOptions(opts);
let resp = pxtc.compile(opts)
if (resp.diagnostics && resp.diagnostics.length > 0) {
resp.diagnostics.forEach(diag => {
console.error(diag.messageText)
})
}
return resp
})
}
export function generateHexFileAsync(options: SimulateOptions): Promise<string> {
return loadPackageAsync(options.id)
.then(() => compileAsync(true, opts => {
if (options.code) opts.fileSystem["main.ts"] = options.code;
}))
.then(resp => {
if (resp.diagnostics && resp.diagnostics.length > 0) {
console.error("Diagnostics", resp.diagnostics)
}
return resp.outfiles[pxtc.BINARY_HEX];
});
}
export function generateVMFileAsync(options: SimulateOptions): Promise<any> {
pxt.setHwVariant("vm")
return loadPackageAsync(options.id)
.then(() => compileAsync(true, opts => {
if (options.code) opts.fileSystem["main.ts"] = options.code;
}))
.then(resp => {
console.log(resp)
return resp
})
}
export async function simulateAsync(container: HTMLElement, simOptions: SimulateOptions): Promise<pxtc.BuiltSimJsInfo> {
const builtSimJS = simOptions.builtJsInfo || await buildSimJsInfo(simOptions);
const {
js,
fnArgs,
parts,
usedBuiltinParts,
} = builtSimJS;
if (!js) {
console.error("Program failed to compile");
return undefined;
}
let options: pxsim.SimulatorDriverOptions = {};
options.onSimulatorCommand = msg => {
if (msg.command === "restart") {
runOptions.storedState = getStoredState(simOptions.id)
driver.run(js, runOptions);
}
if (msg.command == "setstate") {
if (msg.stateKey && msg.stateValue) {
setStoredState(simOptions.id, msg.stateKey, msg.stateValue)
}
}
};
options.messageSimulators = pxt.appTarget?.simulator?.messageSimulators;
let driver = new pxsim.SimulatorDriver(container, options);
let board = pxt.appTarget.simulator.boardDefinition;
let storedState: Map<string> = getStoredState(simOptions.id)
let runOptions: pxsim.SimulatorRunOptions = {
boardDefinition: board,
parts: parts,
builtinParts: usedBuiltinParts,
fnArgs: fnArgs,
cdnUrl: pxt.webConfig.commitCdnUrl,
localizedStrings: Util.getLocalizedStrings(),
highContrast: simOptions.highContrast,
storedState: storedState,
light: simOptions.light,
single: simOptions.single,
};
if (pxt.appTarget.simulator && !simOptions.fullScreen)
runOptions.aspectRatio = parts.length && pxt.appTarget.simulator.partsAspectRatio
? pxt.appTarget.simulator.partsAspectRatio
: pxt.appTarget.simulator.aspectRatio;
driver.run(js, runOptions);
return builtSimJS;
}
export async function buildSimJsInfo(simOptions: SimulateOptions): Promise<pxtc.BuiltSimJsInfo> {
await loadPackageAsync(simOptions.id, simOptions.code, simOptions.dependencies);
let didUpgrade = false;
const currentTargetVersion = pxt.appTarget.versions.target;
let compileResult = await compileAsync(false, opts => {
if (simOptions.assets) {
const parsedAssets = JSON.parse(simOptions.assets);
for (const key of Object.keys(parsedAssets)) {
const el = parsedAssets[key];
opts.fileSystem[key] = el;
if (opts.sourceFiles.indexOf(key) < 0) {
opts.sourceFiles.push(key);
}
if (/\.jres$/.test(key)) {
const parsedJres = JSON.parse(el)
opts.jres = pxt.inflateJRes(parsedJres, opts.jres);
}
}
}
if (simOptions.code) opts.fileSystem["main.ts"] = simOptions.code;
// Api info needed for py2ts conversion, if project is shared in Python
if (opts.target.preferredEditor === pxt.PYTHON_PROJECT_NAME) {
opts.target.preferredEditor = pxt.JAVASCRIPT_PROJECT_NAME;
opts.ast = true;
const resp = pxtc.compile(opts);
const apis = getApiInfo(resp.ast, opts);
opts.apisInfo = apis;
opts.target.preferredEditor = pxt.PYTHON_PROJECT_NAME;
}
// Apply upgrade rules if necessary
const sharedTargetVersion = mainPkg.config.targetVersions?.target;
if (sharedTargetVersion && currentTargetVersion &&
pxt.semver.cmp(pxt.semver.parse(sharedTargetVersion), pxt.semver.parse(currentTargetVersion)) < 0) {
for (const fileName of Object.keys(opts.fileSystem)) {
if (!pxt.Util.startsWith(fileName, "pxt_modules") && pxt.Util.endsWith(fileName, ".ts")) {
didUpgrade = true;
opts.fileSystem[fileName] = pxt.patching.patchJavaScript(sharedTargetVersion, opts.fileSystem[fileName]);
}
}
}
});
if (compileResult.diagnostics?.length > 0 && didUpgrade) {
pxt.log("Compile with upgrade rules failed, trying again with original code");
compileResult = await compileAsync(false, opts => {
if (simOptions.code) opts.fileSystem["main.ts"] = simOptions.code;
});
}
if (compileResult.diagnostics && compileResult.diagnostics.length > 0) {
console.error("Diagnostics", compileResult.diagnostics);
}
return pxtc.buildSimJsInfo(compileResult);
}
function getStoredState(id: string) {
let storedState: Map<any> = {}
try {
let projectStorage = window.localStorage.getItem(id)
if (projectStorage) {
storedState = JSON.parse(projectStorage)
}
} catch (e) { }
return storedState;
}
function setStoredState(id: string, key: string, value: any) {
let storedState: Map<any> = getStoredState(id);
if (!id) {
return
}
if (value)
storedState[key] = value
else
delete storedState[key]
try {
window.localStorage.setItem(id, JSON.stringify(storedState))
} catch (e) { }
}
export enum LanguageMode {
Blocks,
TypeScript
}
export let editorLanguageMode = LanguageMode.Blocks;
export function setEditorContextAsync(mode: LanguageMode, localeInfo: string) {
editorLanguageMode = mode;
if (localeInfo != pxt.Util.localeInfo()) {
const localeLiveRx = /^live-/;
const fetchLive = localeLiveRx.test(localeInfo);
if (fetchLive) {
pxt.Util.enableLiveLocalizationUpdates();
}
return pxt.Util.updateLocalizationAsync({
targetId: pxt.appTarget.id,
baseUrl: pxt.webConfig.commitCdnUrl,
code: localeInfo.replace(localeLiveRx, ''),
pxtBranch: pxt.appTarget.versions.pxtCrowdinBranch,
targetBranch: pxt.appTarget.versions.targetCrowdinBranch,
});
}
return Promise.resolve();
}
function receiveDocMessage(e: MessageEvent) {
let m = e.data as pxsim.SimulatorMessage;
if (!m) return;
switch (m.type) {
case "fileloaded":
let fm = m as pxsim.SimulatorFileLoadedMessage;
let name = fm.name;
setEditorContextAsync(/\.ts$/i.test(name) ? LanguageMode.TypeScript : LanguageMode.Blocks, fm.locale);
break;
case "popout":
let mp = /((\/v[0-9+])\/)?[^\/]*#(doc|md):([^&?:]+)/i.exec(window.location.href);
if (mp) {
const docsUrl = pxt.webConfig.docsUrl || '/--docs';
let verPrefix = mp[2] || '';
let url = mp[3] == "doc" ? (pxt.webConfig.isStatic ? `/docs${mp[4]}.html` : `${mp[4]}`) : `${docsUrl}?md=${mp[4]}`;
// notify parent iframe that we have completed the popout
if (window.parent)
window.parent.postMessage(<pxsim.SimulatorOpenDocMessage>{
type: "opendoc",
url: BrowserUtils.urlJoin(verPrefix, url)
}, "*");
}
break;
case "localtoken":
let dm = m as pxsim.SimulatorDocMessage;
if (dm && dm.localToken) {
Cloud.localToken = dm.localToken;
pendingLocalToken.forEach(p => p());
pendingLocalToken = [];
}
break;
}
}
export function startRenderServer() {
pxt.tickEvent("renderer.ready");
const jobQueue: pxsim.RenderBlocksRequestMessage[] = [];
let jobPromise: Promise<void> = undefined;
function consumeQueue() {
if (jobPromise) return; // other worker already in action
const msg = jobQueue.shift();
if (!msg) return; // no more work
const options = (msg.options || {}) as pxt.blocks.BlocksRenderOptions;
options.splitSvg = false; // don't split when requesting rendered images
pxt.tickEvent("renderer.job")
const isXml = /^\s*<xml/.test(msg.code);
const doWork = async () => {
await pxt.BrowserUtils.loadBlocklyAsync();
const result = isXml
? await pxt.runner.compileBlocksAsync(msg.code, options)
: await runner.decompileSnippetAsync(msg.code, msg.options);
const blocksSvg = result.blocksSvg as SVGSVGElement;
const width = blocksSvg.viewBox.baseVal.width;
const height = blocksSvg.viewBox.baseVal.height;
const res = blocksSvg
? await pxt.blocks.layout.blocklyToSvgAsync(blocksSvg, 0, 0, width, height)
: undefined;
// try to render to png
let png: string;
try {
png = res
? await pxt.BrowserUtils.encodeToPngAsync(res.xml, { width, height })
: undefined;
} catch (e) {
console.warn(e);
}
window.parent.postMessage(<pxsim.RenderBlocksResponseMessage>{
source: "makecode",
type: "renderblocks",
id: msg.id,
width: res?.width,
height: res?.height,
svg: res?.svg,
uri: png || res?.xml,
css: res?.css
}, "*");
}
jobPromise = doWork()
.catch(e => {
window.parent.postMessage(<pxsim.RenderBlocksResponseMessage>{
source: "makecode",
type: "renderblocks",
id: msg.id,
error: e.message
}, "*");
})
.finally(() => {
jobPromise = undefined;
consumeQueue();
})
}
pxt.editor.initEditorExtensionsAsync()
.then(() => {
// notify parent that render engine is loaded
window.addEventListener("message", function (ev) {
const msg = ev.data as pxsim.RenderBlocksRequestMessage;
if (msg.type == "renderblocks") {
jobQueue.push(msg);
consumeQueue();
}
}, false);
window.parent.postMessage(<pxsim.RenderReadyResponseMessage>{
source: "makecode",
type: "renderready",
versions: pxt.appTarget.versions
}, "*");
})
}
export function startDocsServer(loading: HTMLElement, content: HTMLElement, backButton?: HTMLElement) {
pxt.tickEvent("docrenderer.ready");
const history: string[] = [];
if (backButton) {
backButton.addEventListener("click", () => {
goBack();
});
setElementDisabled(backButton, true);
}
function render(doctype: string, src: string) {
pxt.debug(`rendering ${doctype}`);
if (backButton) $(backButton).hide()
$(content).hide()
$(loading).show()
U.delay(100) // allow UI to update
.then(() => {
switch (doctype) {
case "print":
const data = window.localStorage["printjob"];
delete window.localStorage["printjob"];
return renderProjectFilesAsync(content, JSON.parse(data), undefined, true)
.then(() => pxsim.print(1000));
case "project":
return renderProjectFilesAsync(content, JSON.parse(src))
.then(() => pxsim.print(1000));
case "projectid":
return renderProjectAsync(content, JSON.parse(src))
.then(() => pxsim.print(1000));
case "doc":
return renderDocAsync(content, src);
case "book":
return renderBookAsync(content, src);
default:
return renderMarkdownAsync(content, src);
}
})
.catch(e => {
$(content).html(`
<img style="height:4em;" src="${pxt.appTarget.appTheme.docsLogo}" />
<h1>${lf("Oops")}</h1>
<h3>${lf("We could not load the documentation, please check your internet connection.")}</h3>
<button class="ui button primary" id="tryagain">${lf("Try Again")}</button>`);
$(content).find('#tryagain').click(() => {
render(doctype, src);
})
// notify parent iframe that docs weren't loaded
if (window.parent)
window.parent.postMessage(<pxsim.SimulatorDocMessage>{
type: "docfailed",
docType: doctype,
src: src
}, "*");
}).finally(() => {
$(loading).hide()
if (backButton) $(backButton).show()
$(content).show()
})
.then(() => { });
}
function pushHistory() {
if (!backButton) return;
history.push(window.location.hash);
if (history.length > 10) {
history.shift();
}
if (history.length > 1) {
setElementDisabled(backButton, false);
}
}
function goBack() {
if (!backButton) return;
if (history.length > 1) {
// Top is current page
history.pop();
window.location.hash = history.pop();
}
if (history.length <= 1) {
setElementDisabled(backButton, true);
}
}
function setElementDisabled(el: HTMLElement, disabled: boolean) {
if (disabled) {
pxsim.U.addClass(el, "disabled");
el.setAttribute("aria-disabled", "true");
} else {
pxsim.U.removeClass(el, "disabled");
el.setAttribute("aria-disabled", "false");
}
}
function renderHash() {
let m = /^#(doc|md|tutorial|book|project|projectid|print):([^&?:]+)(:([^&?:]+):([^&?:]+))?/i.exec(window.location.hash);
if (m) {
pushHistory();
// navigation occured
const p = m[4] ? setEditorContextAsync(
/^blocks$/.test(m[4]) ? LanguageMode.Blocks : LanguageMode.TypeScript,
m[5]) : Promise.resolve();
p.then(() => render(m[1], decodeURIComponent(m[2])));
}
}
let promise = pxt.editor.initEditorExtensionsAsync();
promise.then(() => {
window.addEventListener("message", receiveDocMessage, false);
window.addEventListener("hashchange", () => {
renderHash();
}, false);
parent.postMessage({ type: "sidedocready" }, "*");
// delay load doc page to allow simulator to load first
setTimeout(() => renderHash(), 1);
})
}
export function renderProjectAsync(content: HTMLElement, projectid: string): Promise<void> {
return Cloud.privateGetTextAsync(projectid + "/text")
.then(txt => JSON.parse(txt))
.then(files => renderProjectFilesAsync(content, files, projectid));
}
export function renderProjectFilesAsync(content: HTMLElement, files: Map<string>, projectid: string = null, escapeLinks = false): Promise<void> {
const cfg = (JSON.parse(files[pxt.CONFIG_NAME]) || {}) as PackageConfig;
let md = `# ${cfg.name} ${cfg.version ? cfg.version : ''}
`;
const readme = "README.md";
if (files[readme])
md += files[readme].replace(/^#+/, "$0#") + '\n'; // bump all headers down 1
cfg.files.filter(f => f != pxt.CONFIG_NAME && f != readme)
.filter(f => (editorLanguageMode == LanguageMode.Blocks) == /\.blocks?$/.test(f))
.forEach(f => {
if (!/^main\.(ts|blocks)$/.test(f))
md += `
## ${f}
`;
if (/\.ts$/.test(f)) {
md += `\`\`\`typescript
${files[f]}
\`\`\`
`;
} else if (/\.blocks?$/.test(f)) {
md += `\`\`\`blocksxml
${files[f]}
\`\`\`
`;
} else {
md += `\`\`\`${f.substr(f.indexOf('.'))}
${files[f]}
\`\`\`
`;
}
});
const deps = cfg && cfg.dependencies && Object.keys(cfg.dependencies).filter(k => k != pxt.appTarget.corepkg);
if (deps && deps.length) {
md += `
## ${lf("Extensions")} #extensions
${deps.map(k => `* ${k}, ${cfg.dependencies[k]}`).join('\n')}
\`\`\`package
${deps.map(k => `${k}=${cfg.dependencies[k]}`).join('\n')}
\`\`\`
`;
}
if (projectid) {
let linkString = (pxt.appTarget.appTheme.shareUrl || "https://makecode.com/") + projectid;
if (escapeLinks) {
// If printing the link will show up twice if it's an actual link
linkString = "`" + linkString + "`";
}
md += `
${linkString}
`;
}
console.debug(`print md: ${md}`);
const options: RenderMarkdownOptions = {
print: true
}
return renderMarkdownAsync(content, md, options);
}
function renderDocAsync(content: HTMLElement, docid: string): Promise<void> {
docid = docid.replace(/^\//, "");
return pxt.Cloud.markdownAsync(docid)
.then(md => renderMarkdownAsync(content, md, { path: docid }))
}
function renderBookAsync(content: HTMLElement, summaryid: string): Promise<void> {
summaryid = summaryid.replace(/^\//, "");
pxt.tickEvent('book', { id: summaryid });
pxt.log(`rendering book from ${summaryid}`)
// display loader
const $loader = $("#loading").find(".loader");
$loader.addClass("text").text(lf("Compiling your book (this may take a minute)"));
// start the work
let toc: TOCMenuEntry[];
return U.delay(100)
.then(() => pxt.Cloud.markdownAsync(summaryid))
.then(summary => {
toc = pxt.docs.buildTOC(summary);
pxt.log(`TOC: ${JSON.stringify(toc, null, 2)}`)
const tocsp: TOCMenuEntry[] = [];
pxt.docs.visitTOC(toc, entry => {
if (/^\//.test(entry.path) && !/^\/pkg\//.test(entry.path))
tocsp.push(entry);
});
return U.promisePoolAsync(4, tocsp, async entry => {
try {
const md = await pxt.Cloud.markdownAsync(entry.path);
entry.markdown = md;
} catch (e) {
entry.markdown = `_${entry.path} failed to load._`;
}
});
})
.then(pages => {
let md = toc[0].name;
pxt.docs.visitTOC(toc, entry => {
if (entry.markdown)
md += '\n\n' + entry.markdown
});
return renderMarkdownAsync(content, md);
})
}
const template = `
<aside id=button class=box>
<a class="ui primary button" href="@ARGS@">@BODY@</a>
</aside>
<aside id=vimeo>
<div class="ui two column stackable grid container">
<div class="column">
<div class="ui embed mdvid" data-source="vimeo" data-id="@ARGS@" data-placeholder="/thumbnail/1024/vimeo/@ARGS@" data-icon="video play">
</div>
</div></div>
</aside>
<aside id=youtube>
<div class="ui two column stackable grid container">
<div class="column">
<div class="ui embed mdvid" data-source="youtube" data-id="@ARGS@" data-placeholder="https://img.youtube.com/vi/@ARGS@/0.jpg">
</div>
</div></div>
</aside>
<aside id=section>
<!-- section @ARGS@ -->
</aside>
<aside id=hide class=box>
<div style='display:none'>
@BODY@
</div>
</aside>
<aside id=avatar class=box>
<div class='avatar @ARGS@'>
<div class='avatar-image'></div>
<div class='ui compact message'>
@BODY@
</div>
</div>
</aside>
<aside id=hint class=box>
<div class="ui info message">
<div class="content">
@BODY@
</div>
</div>
</aside>
<aside id=codecard class=box>
<pre><code class="lang-codecard">@BODY@</code></pre>
</aside>
<aside id=tutorialhint class=box>
<div class="ui hint message">
<div class="content">
@BODY@
</div>
</div>
</aside>
<aside id=reminder class=box>
<div class="ui warning message">
<div class="content">
@BODY@
</div>
</div>
</aside>
<aside id=alert class=box>
<div class="ui negative message">
<div class="content">
@BODY@
</div>
</div>
</aside>
<aside id=tip class=box>
<div class="ui positive message">
<div class="content">
@BODY@
</div>
</div>
</aside>
<!-- wrapped around ordinary content -->
<aside id=main-container class=box>
<div class="ui text">
@BODY@
</div>
</aside>
<!-- used for 'column' box - they are collected and wrapped in 'column-container' -->
<aside id=column class=aside>
<div class='column'>
@BODY@
</div>
</aside>
<aside id=column-container class=box>
<div class="ui three column stackable grid text">
@BODY@
</div>
</aside>
@breadcrumb@
@body@`;
export interface RenderMarkdownOptions {
path?: string;
tutorial?: boolean;
blocksAspectRatio?: number;
print?: boolean; // render for print
}
export function renderMarkdownAsync(content: HTMLElement, md: string, options: RenderMarkdownOptions = {}): Promise<void> {
const html = pxt.docs.renderMarkdown({
template: template,
markdown: md,
theme: pxt.appTarget.appTheme