-
Notifications
You must be signed in to change notification settings - Fork 2
/
ext.js
91 lines (78 loc) · 2.63 KB
/
ext.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
(function(ext) {
ext.read = function(dir, callback) {
makeRequestToHelperApp('GET', dir, callback);
};
ext.write = function(text, dir, callback) {
makeRequestToHelperApp('PUT', dir, callback, text);
};
ext.append = function(text, dir, callback) {
makeRequestToHelperApp('PUT', dir, callback, text, "append");
};
ext.make = function(dir, callback) {
makeRequestToHelperApp('POST', dir, callback);
};
ext.newline_char = function() {
return '\n';
}
var helperDetected = false;
var intervals = {};
ext._shutdown = function(){
for(var prop in intervals) {
if(intervals.hasOwnProperty(prop))
window.clearInterval(prop);
}
};
ext._getStatus = function() {
if(helperDetected)
return {status:2, msg:'Ready'};
else
return {status:1, msg:'Waiting for Helper App'};
};
ScratchExtensions.register('Simple File I/O',
{
blocks: [
['R', 'read from file %s', 'read', 'text.txt'],
['w', 'write %s to file %s', 'write', 'hello world', 'text.txt'],
['w', 'append %s to file %s', 'append', 'hello world', 'text.txt'],
['w', 'create file %s', 'make', 'text.txt'],
['r', 'newline', 'newline_char']
],
url: 'http://znapi.github.io/scratchx-file-io/'
},
ext);
function makeRequestToHelperApp(method, uri, callback, body, action) {
var intervalID;
function request(method, uri, body, action, onSuccess, onFailure) {
var r = new XMLHttpRequest();
r.onreadystatechange = function() {
if(r.readyState === 4) {
if(r.getResponseHeader('X-Is-ScratchX-File-IO-Helper-App')==='yes')
onSuccess(r.responseText);
else
onFailure();
}
};
r.open(method, 'http://localhost:8080/'+uri, true);
if(action !== undefined)
r.setRequestHeader("X-Action", action);
if(body !== undefined)
r.send(body);
else
r.send();
}
request(method, uri, body, action,
callback,
function() {
helperDetected = false;
intervalID = window.setInterval(request, 5000, method, uri, body, action,
function(rsp) {window.clearInterval(intervalID); delete intervals[intervalID]; helperDetected=true; callback(rsp)},
function() {}
);
intervals[intervalID] = undefined;
}
);
}
makeRequestToHelperApp('OPTIONS', '', function() {
helperDetected = true;
});
})({});