-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmakecode-render-blocks.ts
More file actions
315 lines (293 loc) · 8.91 KB
/
makecode-render-blocks.ts
File metadata and controls
315 lines (293 loc) · 8.91 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
/**
* MakeCode handling that does not depend on React.
*/
import { BlockLayout, MakeCodeProject } from './pxt.js';
const disposedMessage = 'Disposed';
const makecodeFailedToLoadMessage = 'Failed to load MakeCode to render blocks.';
type MakeCodeState = 'disabled' | 'loading' | 'error' | 'ready';
export interface MakeCodeRenderBlocksOptions {
// Avoids loading MakeCode if set.
disabled?: boolean;
version?: string;
lang?: string;
baseUrl?: string;
}
export interface MakeCodeRenderBlocksReturn {
renderBlocks: (req: RenderBlocksRequest) => Promise<RenderBlocksResponse>;
initialize: () => void;
dispose: () => void;
}
export interface RenderBlocksRequest {
code: string | MakeCodeProject;
options?: {
packageId?: string;
package?: string;
snippetMode?: boolean;
layout?: BlockLayout;
};
}
export interface RenderBlocksResponse {
uri?: string;
css?: string;
svg?: string;
width?: number;
height?: number;
}
interface RenderBlocksRequestMessage {
type: 'renderblocks';
// The ID is required by MakeCode but we set it.
id?: string;
code: string;
options?: {
packageId?: string;
package?: string;
snippetMode?: boolean;
layout?: BlockLayout;
assets?: Record<string, string>;
};
}
interface RenderBlocksResponseMessage {
source: 'makecode';
type: 'renderblocks';
id: string;
uri?: string;
css?: string;
svg?: string;
width?: number;
height?: number;
error?: string;
}
type RequestInputType = 'text' | 'blocks';
interface RenderBlocksRequestResponse {
input: MakeCodeProject | string;
sent: boolean;
type: RequestInputType;
req: RenderBlocksRequestMessage;
promise: {
resolve: (v: RenderBlocksResponseMessage) => void;
reject: (err: string) => void;
};
}
type PendingRequests = { [id: string]: RenderBlocksRequestResponse };
export const createMakeCodeRenderBlocks = (
options: MakeCodeRenderBlocksOptions
): MakeCodeRenderBlocksReturn => {
const defaultedOptions: MakeCodeRenderBlocksOptions = {
...options,
};
const makecodeOrigin = options.baseUrl ?? 'https://makecode.microbit.org';
let iframe: HTMLIFrameElement | undefined;
let status: MakeCodeState = 'loading';
const requestStatus = {
nextRequest: 0,
pendingRequests: {} as PendingRequests,
};
const pendingRequests = requestStatus.pendingRequests;
const failAllPending = (errorMessage: string) => {
Object.keys(requestStatus.pendingRequests).forEach((k) => {
const { promise } = pendingRequests[k];
delete pendingRequests[k];
promise.reject(errorMessage);
});
};
const sendPendingIfReady = () => {
if (status === 'ready') {
// Possible that dispose has been called by the time we process the message,
// in which case do nothing.
if (iframe) {
Object.values(pendingRequests).forEach((rr) => ensureMessageSent(rr));
}
} else if (status === 'error') {
failAllPending(makecodeFailedToLoadMessage);
} else if (status === 'disabled') {
failAllPending('renderBlocks will always fail when explicitly disabled');
} else {
// We're loading, we'll send these when done.
}
};
const ensureMessageSent = (rr: RenderBlocksRequestResponse) => {
if (!rr.sent) {
rr.sent = true;
const { req } = rr;
iframe!.contentWindow!.postMessage(req, makecodeOrigin);
}
};
const findBestCode = (
code: string | MakeCodeProject,
ignoreBlocks?: boolean
): { type: RequestInputType; code: string } => {
if (typeof code === 'string') {
return { code, type: 'text' };
}
if (code.text) {
const blocks = code.text['main.blocks'];
const text = code.text['main.ts'];
if (blocks && !ignoreBlocks) {
return {
code: blocks,
type: 'blocks',
};
}
if (text) {
return {
code: text,
type: 'text',
};
}
}
return { code: '', type: 'text' };
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let errorTimeout: any;
const handleMessage = (ev: MessageEvent) => {
const msg = ev.data;
if (ev.source !== iframe?.contentWindow || msg.source !== 'makecode') {
return;
}
switch (msg.type) {
case 'renderready': {
window.clearTimeout(errorTimeout);
status = 'ready';
sendPendingIfReady();
break;
}
case 'renderblocks': {
const id: string = msg.id;
const matchingRequest = pendingRequests[id];
if (!matchingRequest) {
return;
}
const result = msg as RenderBlocksResponseMessage;
// This currently happens for extension blocks.
// We retry with text based rendering.
// MakeCode beta appears to do this internally.
if (
!result.error &&
!result.width &&
!result.height &&
!result.svg &&
!result.uri
) {
if (matchingRequest.type === 'blocks') {
matchingRequest.sent = false;
matchingRequest.type = 'text';
matchingRequest.req.code = findBestCode(
matchingRequest.input,
true
).code;
ensureMessageSent(matchingRequest);
return;
} else {
result.error = 'Internal MakeCode failure.';
}
}
delete pendingRequests[id];
if (result.error) {
matchingRequest.promise.reject(result.error);
} else {
matchingRequest.promise.resolve(msg as RenderBlocksResponseMessage);
}
break;
}
}
};
return {
initialize: () => {
if (options.disabled) {
return;
}
window.addEventListener('message', handleMessage);
iframe = createIframe(makecodeOrigin, defaultedOptions);
errorTimeout = setTimeout(() => {
failAllPending(makecodeFailedToLoadMessage);
status = 'error';
}, 30000);
},
dispose: () => {
window.clearTimeout(errorTimeout);
window.removeEventListener('message', handleMessage);
if (iframe && iframe.parentNode) {
iframe.parentNode.removeChild(iframe);
}
iframe = undefined;
failAllPending(disposedMessage);
},
renderBlocks: (req: RenderBlocksRequest): Promise<RenderBlocksResponse> => {
const id = requestStatus.nextRequest++ + '';
const { code, type } = findBestCode(req.code);
const makecodeRequest: RenderBlocksRequestMessage = {
id,
code,
type: 'renderblocks',
options: {
...req.options,
// To include files to filesystem
assets: typeof req.code === 'object' ? req.code.text : undefined,
package: defaultPackageFromDependencies(req),
},
};
return new Promise((resolve, reject) => {
pendingRequests[id] = {
type,
input: req.code,
sent: false,
req: makecodeRequest,
promise: { resolve, reject },
};
sendPendingIfReady();
});
},
};
};
function defaultPackageFromDependencies(
req: RenderBlocksRequest
): string | undefined {
// Package can encode the extensions used in a comma separated list in this format:
// automationbit=github:pimoroni/pxt-automationbit#v0.0.2
// We can find that list from the JSON passed (but not from blocks or text)
const _package =
req.options && req.options.package ? req.options.package : undefined;
if (
typeof _package === 'undefined' &&
typeof req.code === 'object' &&
req.code.text!['pxt.json']
) {
const parsed = JSON.parse(req.code.text!['pxt.json']);
if (typeof parsed === 'object') {
// Cope with extensions with spaces in their names. Otherwise pxt rejects
// adding the dependency even if it would in normal usage.
// https://github.com/microbit-foundation/classroom-management-tool/issues/463
const sanitizedName = (s: string) => s.replace(/[^a-zA-Z0-9_-]/g, '_');
const dependencies: Record<string, string> = parsed.dependencies || {};
const result = Object.keys(dependencies)
.map((name) => `${sanitizedName(name)}=${dependencies[name]}`)
.join(',');
return result;
}
}
return _package;
}
function createIframe(
makecodeOrigin: string,
{ lang, version, baseUrl }: MakeCodeRenderBlocksOptions
): HTMLIFrameElement {
const query = `?render=1${lang ? `&lang=${encodeURIComponent(lang)}` : ''}`;
const src = baseUrl
? makecodeOrigin + query
: [makecodeOrigin, version, '--docs'].filter(Boolean).join('/') + query;
const f = document.createElement('iframe');
f.style.position = 'absolute';
f.style.width = '1px';
f.style.height = '1px';
f.style.border = '0';
f.style.clip = 'rect(0 0 0 0)';
f.style.margin = '-1px';
f.style.padding = '0';
f.style.overflow = 'hidden';
f.style.whiteSpace = 'nowrap';
f.setAttribute('loading', 'eager');
f.setAttribute('aria-hidden', 'true');
f.src = src;
document.body.appendChild(f);
return f;
}