-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmakecode-frame-driver.ts
More file actions
826 lines (755 loc) · 21.3 KB
/
makecode-frame-driver.ts
File metadata and controls
826 lines (755 loc) · 21.3 KB
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
import {
EditorContentLoadedRequest,
EditorEvent,
EditorMessageGetToolboxCategoriesRequest,
EditorMessageGetToolboxCategoriesResponse,
EditorMessageImportExternalProjectRequest,
EditorMessageImportExternalProjectResponse,
EditorMessageImportProjectRequest,
EditorMessageImportTutorialRequest,
EditorMessageNewProjectRequest,
EditorMessageOpenHeaderRequest,
EditorMessageRenderByBlockIdResponse,
EditorMessageRenderPythonResponse,
EditorMessageRenderXmlResponse,
EditorMessageRequest,
EditorMessageResponse,
EditorMessageSetHighContrastRequest,
EditorMessageSetScaleRequest,
EditorMessageSetSimulatorFullScreenRequest,
EditorMessageTutorialEventRequest,
EditorSetLanguageRestriction,
EditorShareResponse,
EditorWorkspaceEvent,
EditorWorkspaceSaveRequest,
EditorWorkspaceSyncRequest,
EditorWorkspaceSyncResponse,
ImportExternalProjectOptions,
ImportFileOptions,
ImportProjectOptions,
InfoMessage,
LanguageRestriction,
MakeCodeProject,
ProjectCreationOptions,
ProjectFilters,
RenderBlocksOptions,
RenderByBlockIdOptions,
RenderXmlOptions,
ShareResult,
StartActivityOptions,
ToolboxCategoryDefinition,
} from './pxt.js';
// Adapts the MakeCode types into a discriminated union
type EditorMessageRequestUnion =
| EditorMessageSetScaleRequest
| EditorMessageGetToolboxCategoriesRequest
| EditorMessageImportExternalProjectRequest
| EditorMessageImportProjectRequest
| EditorMessageImportTutorialRequest
| EditorMessageNewProjectRequest
| EditorMessageRequest;
export interface EditorShareOptions {
headerId: string;
projectName: string;
}
export interface Options {
/**
* A function that provides the initial set of projects to be used when initialising MakeCode.
*
* This will also be used if the iframe reloads itself.
*
* The projects will receive updates via `onWorkspaceSave` and should be stored keyed by header
* id.
*/
initialProjects: () => Promise<MakeCodeProject[]>;
/**
* Set this to a value representing your app.
*/
controllerId?: string;
/**
* Filters affecting the configuration of MakeCode.
*/
filters?: ProjectFilters;
/**
* Whether to show the search bar.
*/
searchBar?: boolean;
/**
* Called when the main editor area is ready (e.g. after a project load).
*/
onEditorContentLoaded?(event: EditorContentLoadedRequest): void;
/**
* This is not typically needed as the driver responds to MakeCode's request to sync using the initialProjects option.
*/
onWorkspaceSync?(event: EditorWorkspaceSyncRequest): void;
/**
* Called when the workspace sync is complete.
*/
onWorkspaceLoaded?(event: EditorWorkspaceSyncRequest): void;
/**
* Implement this to update the data store that `initialProjects` reads from.
*/
onWorkspaceSave?(event: EditorWorkspaceSaveRequest): void;
/**
* This is only called via MakeCode UI, which is not visible in embedded mode.
*
* It's intention is to delete all projects/settings.
*/
onWorkspaceReset?(event: EditorWorkspaceSyncRequest): void;
/**
* Editor events including detail on block usage and help interactions.
*/
onWorkspaceEvent?(event: EditorEvent): void;
/**
* Updates as a user progresses through a tutorial.
*/
onTutorialEvent?(event: EditorMessageTutorialEventRequest): void;
/**
* Requests the embedding app handles a download.
*
* Applies only with `controller` set to `2`.
*/
onDownload?: (download: { name: string; hex: string }) => void;
/**
* Requests the embedding app handles a save.
*
* Applies only with `controller` set to `2`.
*/
onSave?: (save: { name: string; hex: string }) => void;
/**
* Requests the embedding app handles a press/tap on the back arrow.
*
* Applies only with `controller` set to `2`.
*/
onBack?: () => void;
/**
* Requests the embedding app handles a long press/tap on the back arrow.
* This is optional.
*
* Applies only with `controller` set to `2`.
*/
onBackLongPress?: () => void;
}
/**
* A driver for MakeCode.
*
* This stores state to correlate requests/responses to and from MakeCode.
*/
export class MakeCodeFrameDriver {
private ready = false;
private messageQueue: Array<unknown> = [];
private nextId = 0;
private pendingResponses = new Map<
string,
{
resolve: (value: unknown) => void;
reject: (value: unknown) => void;
message: unknown;
}
>();
private _expectedOrigin: string | undefined;
private expectedOrigin = () => {
if (this._expectedOrigin) {
return this._expectedOrigin;
}
const src = this.iframe()?.src;
if (src) {
this._expectedOrigin = new URL(src).origin;
return this._expectedOrigin;
}
return undefined;
};
private listener = (event: MessageEvent) => {
const expectedOrigin = this.expectedOrigin();
if (!expectedOrigin || event.origin !== expectedOrigin) {
return;
}
const { data } = event;
if (typeof data !== 'object') {
return;
}
// I think 'editorcontentloaded' isn't useful here in controller scenarios but needs confirming.
// Might be the right option when waiting to render blocks or similar?
if (
data.type === 'iframeclientready' ||
(data.type === 'pxthost' && data.action === 'editorcontentloaded')
) {
this.ready = true;
this.messageQueue.forEach((m) => this.sendMessageNoReadyCheck(m));
this.messageQueue.length = 0;
}
if (data.type === 'pxteditor') {
// A reply to a message we sent. Some of these have useful data in a
// semi-standard resp field but others have useful top-level fields so we
// leave it to the caller to handle each message type.
const pendingResponse = this.pendingResponses.get(data.id);
if (pendingResponse) {
this.pendingResponses.delete(data.id);
const { resolve, reject } = pendingResponse;
if (data.success) {
resolve(data);
} else {
reject(
data.error ??
new Error(
'MakeCode response was not successful with no error specified'
)
);
}
}
} else if (data.type === 'pxthost') {
this.handleWorkspaceSync(data);
switch (data.action) {
case 'event': {
// Can't make these happen.
// Might require "allowSimTelemetry". But even then I can only see them fired with type: "pxtsim".
return;
}
case 'simevent': {
// So far as I can tell these don't fire.
// The logic in MakeCode doesn't seem to allow them in controller mode, only if allowParentController is set.
// In other scenarios either being true is sufficient.
return;
}
case 'tutorialevent': {
return this.options.onTutorialEvent?.(
data as EditorMessageTutorialEventRequest
);
}
case 'workspacesave': {
return this.options.onWorkspaceSave?.(
data as EditorWorkspaceSaveRequest
);
}
case 'workspaceevent': {
return this.options.onWorkspaceEvent?.(
(data as EditorWorkspaceEvent).event
);
}
case 'workspacereset': {
return this.options.onWorkspaceReset?.(
data as EditorWorkspaceSyncRequest
);
}
case 'workspacesync': {
return this.options.onWorkspaceSync?.(
data as EditorWorkspaceSyncRequest
);
}
case 'workspaceloaded': {
return this.options.onWorkspaceLoaded?.(
data as EditorWorkspaceSyncRequest
);
}
case 'workspacediagnostics': {
// So far as I can tell these don't fire.
// The logic in MakeCode doesn't seem to allow them in controller mode, only if allowParentController is set.
// In other scenarios either being true is sufficient.
return;
}
case 'editorcontentloaded': {
return this.options.onEditorContentLoaded?.(
data as EditorContentLoadedRequest
);
}
case 'projectcloudstatus': {
// Requesting cloud status likely only works on the same domain as MakeCode
// so isn't implemented.
return;
}
}
} else if ('download' in data) {
// Native app oriented event that doesn't have a 'type' field.
this.options.onDownload?.({
name: data.name,
hex: data.download,
});
} else if ('save' in data) {
// Native app oriented event that doesn't have a 'type' field.
this.options.onSave?.({
name: data.name,
hex: data.save,
});
} else if ('cmd' in data) {
// Native app oriented event that doesn't have a 'type' field.
switch (data.cmd) {
case 'backtap':
// MakeCode seems to send this twice for a single click but there's little we can do here.
return this.options.onBack?.();
case 'backpress':
return this.options.onBackLongPress?.();
}
}
};
constructor(
private options: Options,
private iframe: () => HTMLIFrameElement | undefined
) {}
initialize() {
window.addEventListener('message', this.listener);
// If the iframe is already loaded this will ensure we still initialize correctly
this.iframe()?.contentWindow?.postMessage(
{
type: 'iframeclientready',
},
'*'
);
}
setOptions(options: Options) {
this.options = options;
}
dispose() {
window.removeEventListener('message', this.listener);
}
private sendRequest = (
message: EditorMessageRequestUnion
): Promise<unknown> => {
message.response = true;
if (!message.id) {
message.id = (this.nextId++).toString();
}
const id = message.id;
const p = new Promise((resolve, reject) => {
this.pendingResponses.set(id, { resolve, reject, message });
});
this.sendMessage(message);
return p;
};
private sendMessage = (message: unknown) => {
if (this.ready) {
this.sendMessageNoReadyCheck(message);
} else {
this.messageQueue.push(message);
}
};
private sendMessageNoReadyCheck = (message: unknown) => {
this.iframe()?.contentWindow?.postMessage(message, '*');
};
private async handleWorkspaceSync(
event: EditorWorkspaceSyncRequest | EditorWorkspaceSaveRequest
) {
let error: unknown = undefined;
try {
if (event.action === 'workspacesync') {
const projects = await this.options.initialProjects();
const { filters, searchBar, controllerId } = this.options;
// I think the MakeCode driver waits for ready here but that doesn't work with live MakeCode.
this.sendMessageNoReadyCheck({
...event,
success: true,
projects,
controllerId,
editor: {
filters,
searchBar,
},
} as EditorWorkspaceSyncResponse);
} else if (event.action === 'workspacesave') {
this.options.onWorkspaceSave?.(event);
}
} catch (e) {
error = e;
console.error(e);
} finally {
if (event.response) {
this.sendMessageNoReadyCheck({
type: 'pxthost',
id: event.id,
success: !error,
error,
} as EditorMessageResponse);
}
}
}
/**
* Switch the MakeCode to blocks mode.
*
* You can find the current mode in the project.
*/
async switchBlocks(): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'switchblocks',
});
}
/**
* Switch the MakeCode to JavaScript mode.
*
* You can find the current mode in the project.
*/
async switchJavascript(): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'switchjavascript',
});
}
/**
* Switch the MakeCode to JavaScript mode.
*
* You can find the current mode in the project.
*/
async switchPython(): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'switchpython',
});
}
/**
* Start the simulator.
*/
async startSimulator(): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'startsimulator',
});
}
/**
* Restarts the simulator.
*/
async restartSimulator(): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'restartsimulator',
});
}
/**
* Stops the simulator.
*/
async stopSimulator(options?: {
/**
* Optionally unload the simulator (removes its UI)
*/
unload: boolean;
}): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'stopsimulator',
...options,
});
}
/**
* Hides the simulator. The user can reverse this via the UI.
*/
async hideSimulator(): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'hidesimulator',
});
}
/**
* Show the simulator. The user can reverse this via the UI.
*/
async showSimulator(): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'showsimulator',
});
}
/**
* Closes the toolbox and similar UX.
*/
async closeFlyout(): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'closeflyout',
});
}
/**
* Create a new project.
*/
async newProject(options?: ProjectCreationOptions): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'newproject',
options,
});
}
/**
* Import a project.
*
* The project needs to have a header.
* Otherwise consider `newProject`
*/
async importProject(options: ImportProjectOptions): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'importproject',
...options,
});
}
/**
* Create a URL that can be used to import a project into MakeCode.
*
* This can be useful if MakeCode is embedded in one application but you want to be able to export to non-embedded MakeCode.
*
* The applications must be part of the same site as the process relies on shared client-side storage.
*
* The URL must be used immediately as it won't remain valid if another call is made.
*/
async importExternalProject(
options: ImportExternalProjectOptions
): Promise<{ importUrl: string }> {
const response = (await this.sendRequest({
type: 'pxteditor',
action: 'importexternalproject',
...options,
})) as EditorMessageImportExternalProjectResponse;
return response.resp;
}
/**
* Import a tutorial from markdown text.
*
* See also `startActivity`.
*/
async importTutorial(options: { markdown: string }): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'importtutorial',
...options,
});
}
/**
* Open a MakeCode project.
*/
async openHeader(headerId: string): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'openheader',
headerId,
} as EditorMessageOpenHeaderRequest);
}
/**
* Undo.
*/
async undo(): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'undo',
});
}
/**
* Redo.
*/
async redo(): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'redo',
});
}
// It's confusingly different from https://makecode.microbit.org/blocks-embed#:~:text=Render%20Blocks%20Response%20message,as%20an%20image%20data%20source
// Would be good to see if it takes all those options in practice.
async renderBlocks(options: RenderBlocksOptions): Promise<string> {
const result = (await this.sendRequest({
type: 'pxteditor',
action: 'renderblocks',
...options,
})) as { resp: string };
return result.resp;
}
async renderPython(options: { ts: string }): Promise<string | undefined> {
const { resp } = (await this.sendRequest({
type: 'pxteditor',
action: 'renderpython',
...options,
})) as EditorMessageRenderPythonResponse;
return resp;
}
async renderXml(options: RenderXmlOptions): Promise<string | undefined> {
const { resp } = (await this.sendRequest({
type: 'pxteditor',
action: 'renderxml',
...options,
})) as EditorMessageRenderXmlResponse;
return resp;
}
/**
* Renders an individual block by type (e.g. basic_show_id) to an SVG data URI.
*/
async renderByBlockId(
options: RenderByBlockIdOptions
): Promise<string | undefined> {
const { resp } = (await this.sendRequest({
type: 'pxteditor',
action: 'renderbyblockid',
...options,
})) as EditorMessageRenderByBlockIdResponse;
return resp;
}
async setScale({ scale }: { scale: number }): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'setscale',
scale,
});
}
/**
* See https://github.com/microsoft/pxt-microbit/issues/5456
*
* Tutorial tool sharing link ID from https:*makecode.com/tutorial-tool prefixed with 'S'
* path: 'S96773-99918-18806-19059',
*
* Built-in tutorial
* path: '/projects/rock-paper-scissors',
*
* GitHub repo (no trailing .md, no blob/main cruft, tag versions)
*
* You get a series of "tutorialevent" actions tracking load and progress
* which we'd need to add support for at least to error handle the load.
*/
async startActivity(options: StartActivityOptions): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'startactivity',
...options,
});
}
async saveProject(): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'saveproject',
});
}
async compile(): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'compile',
});
}
async unloadProject(): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'unloadproject',
});
}
async shareProject(options: EditorShareOptions): Promise<ShareResult> {
const { resp } = (await this.sendRequest({
type: 'pxteditor',
action: 'shareproject',
...options,
})) as EditorShareResponse;
return resp;
}
/**
* Change the language restriction (e.g. move to just JavaScript).
*/
async setLanguageRestriction(
restriction: LanguageRestriction
): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'setlanguagerestriction',
restriction,
} as EditorSetLanguageRestriction);
}
async getToolboxCategories(options?: {
advanced?: boolean;
}): Promise<ToolboxCategoryDefinition[]> {
// Oddly the type seems to be for the resp field rather than the message
const {
resp: { categories },
} = (await this.sendRequest({
type: 'pxteditor',
action: 'gettoolboxcategories',
...options,
})) as { resp: EditorMessageGetToolboxCategoriesResponse };
return categories;
}
async toggleDebugSloMo(options?: { invervalSpeed?: number }): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'toggletrace',
...options,
});
}
async setDebugSlowMo(options: {
enabled: boolean;
intervalSpeed?: number;
}): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'settracestate',
...options,
});
}
async toggleHighContrast(): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'togglehighcontrast',
});
}
async setHighContrast(on: boolean): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'sethighcontrast',
on,
} as EditorMessageSetHighContrastRequest);
}
async toggleGreenScreen(): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'togglegreenscreen',
});
}
async setSimulatorFullScreen(enabled: boolean): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'setsimulatorfullscreen',
enabled,
} as EditorMessageSetSimulatorFullScreenRequest);
}
async print(): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'print',
});
}
async pair(): Promise<void> {
await this.sendRequest({
type: 'pxteditor',
action: 'pair',
});
}
async info(): Promise<InfoMessage> {
const { resp } = (await this.sendRequest({
type: 'pxteditor',
action: 'info',
})) as EditorMessageResponse & { resp: InfoMessage };
return resp;
}
/**
* Import a file.
*
* This works with hex and mkcd files.
*
* TODO: Other types may also be supported.
*/
importFile(options: ImportFileOptions): void {
this.sendMessage({
type: 'importfile',
...options,
});
}
}
export const createMakeCodeURL = (
baseUrl: string | undefined,
version: string | undefined,
lang: string | undefined,
controller: number | undefined,
queryParams: Record<string, string> | undefined
): string => {
const url = new URL(
baseUrl + (version ? `/${encodeURIComponent(version)}` : '')
);
if (lang) {
url.searchParams.set('lang', lang);
}
if (controller) {
url.searchParams.set('controller', controller.toString());
}
if (queryParams) {
for (const [k, v] of Object.entries(queryParams)) {
url.searchParams.set(k, v);
}
}
return url.toString();
};