-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse-blocks.js
82 lines (79 loc) · 2.78 KB
/
parse-blocks.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
/**
* Taken from https://pxt.azureedge.net/blob/192ce73678d26c889a124ca45cb225998d50338b//gh-pages-embed.js
* Renders the blocks snippet in an HTML page
* @param targetUrl full editor URL
*/
function parseBlocks(targetUrl) {
if (targetUrl[targetUrl.length - 1] != '/') {
targetUrl += '/'
}
// pre waiting to be rendered
// when undefined, iframe is loaded and ready
var pendingPres = []
function injectRenderer() {
var f = document.getElementById("makecoderenderer")
// check iframe already added to the DOM
if (f) {
return
}
var f = document.createElement("iframe")
f.id = "makecoderenderer"
f.style.position = "absolute"
f.style.left = 0
f.style.bottom = 0
f.style.width = "1px"
f.style.height = "1px"
f.src = targetUrl + "--docs?render=1"
document.body.appendChild(f)
}
function renderPre(pre) {
if(!pre.id) pre.id = Math.random()
var f = document.getElementById("makecoderenderer")
// check if iframe is added and ready (pendingPres is undefined)
if (!f || !!pendingPres) {
// queue up
pendingPres.push(pre)
injectRenderer()
} else {
f.contentWindow.postMessage({
type: "renderblocks",
id: pre.id,
code: pre.innerText,
options: {
snippetMode: pre.classList.contains('snippet'),
}
}, targetUrl)
}
}
// listen for messages
window.addEventListener("message", function (ev) {
var msg = ev.data
if (msg.source != "makecode") return
console.log(msg.type)
switch (msg.type) {
case "renderready":
// flush pending requests
var pres = pendingPres
// set as undefined to notify that iframe is ready
pendingPres = undefined
pres.forEach(function (pre) { renderPre(pre) })
break
case "renderblocks":
var svg = msg.svg // this is an string containing SVG
var id = msg.id // this is the id you sent
// replace text with svg
var img = document.createElement("img")
img.src = msg.uri
img.width = msg.width
img.height = msg.height
var code = document.getElementById(id)
code.parentElement.insertBefore(img, code)
code.parentElement.removeChild(code)
break
}
}, false)
var pres = document.querySelectorAll("pre>code.blocks")
Array.prototype.forEach.call(pres, function (pre) {
renderPre(pre)
})
}