Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

Commit 168dc27

Browse files
Merge pull request bbcmicrobit#370 from bbcmicrobit/embedded-mobile
Update the Editor Controller to support the apps
2 parents 958ab16 + 5e93c77 commit 168dc27

6 files changed

Lines changed: 698 additions & 124 deletions

File tree

‎docs/embedEditor.md‎

Lines changed: 38 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,26 @@
11
# Embedding python editor in the site
22

3-
### Using iframe
3+
## From a mobile app webview
4+
5+
Load the editor with the URL parameter `?mobileApp=1`.
6+
7+
The app needs to subscribe to the following window 'onMessage' events:
8+
- iOS: `window.webkit.messageHandlers.host`
9+
- Android: `window.host`
10+
11+
## Using an iframe
412

513
```
614
<iframe
715
title="Embed python editor"
816
src="http://url/pointing/to/editor?controller=1" />
917
```
1018

11-
To enable embed editor messaging between window and iframe query param "controller=1" should be provided
19+
To enable embed editor messaging between window and iframe query param
20+
"controller=1" should be provided.
1221

13-
For receiving editor's messages you need to subscribe to window event "onMessage"
22+
For receiving editor's messages you need to subscribe to window event
23+
"onMessage".
1424

1525
```
1626
window.addEventListener("message", handleMessageReceive);
@@ -26,35 +36,48 @@ function(event: MessageEvent) {
2636
}
2737
```
2838

29-
For sending messages to editor use
39+
For sending messages to editor use:
3040

3141
```
3242
document.querySelector('iframe').contentWindow.postMessage(EditorMessageData,"*");
3343
```
3444

35-
where EditorMessageData is
45+
where EditorMessageData is the following (optional keys will depend on the
46+
`action` type):
3647

3748
```
3849
{
3950
type: "pyeditor"
4051
action: MessageAction # see supported actions
41-
project?: string # is python code
42-
projects?: string[] # is python code []
52+
project?: string # value is python code
53+
projects?: string[] # value python code []
54+
filename?: string # value is file name
55+
filestring?: string # value is file data
4356
}
4457
```
4558

46-
supported actions:
4759

48-
- workspacesync - Used to sync initial data between parent window and iframe window. Used to receive and send messages (see example bellow).
49-
- workspacesave - received action when the code has changed in the editor
50-
- workspaceloaded - received action when editor fully configured/sync
51-
- importproject - use for sending new code to editor
60+
## Supported Actions
61+
62+
- workspacesync - Used to sync initial data between parent window and iframe
63+
window. Used to receive and send messages (see example bellow).
64+
- workspaceloaded - Notifies controller 'workspacesync' was successful and the
65+
editor is fully configured/sync
66+
- workspacesave - Sends the editor code to the controller, configured to do this
67+
periodically when the code changes
68+
- importproject - Controller sends code to load into the editor
69+
- loadhex - Controller sends a hex file to load into the editor
70+
- loadfile - Controller sends a python file to load into the editor
71+
- loadfile - Controller sends a python file to load into the editor
72+
- savefile - Editor sends a python file to the controller
73+
- flashhex - Editor sends a hex file to the controller
74+
- mobilemode - Change the editor configuration for the mobile apps UX
5275

53-
> received - parent window gets message from editor
76+
More info can be found in the `CONTROLLER_MESSAGING` object in the
77+
`js/editor-controller.js` source file.
5478

55-
> send - parent window sends message to editor
5679

57-
### How synchronize parent window data with embed editor data. For ex. set initial code
80+
## How synchronize parent window data with embed editor data. For ex. set initial code
5881

5982
```
6083
# when action 'workspacesync' received

‎editor.html‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,7 @@ <h2 id="modal-msg-title"></h2>
403403
<script src="lang/en.js" id="lang"></script>
404404
<script src="js/micropythonapi.js"></script>
405405
<script src="js/urlparser.js"></script>
406+
<script src="js/editor-controller.js"></script>
406407
<script src="js/fs.js"></script>
407408
<script src="js/python-main.js"></script>
408409
<script>vex.defaultOptions.className = 'vex-theme-wireframe';</script>

‎js/editor-controller.js‎

Lines changed: 294 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,294 @@
1+
/**
2+
* The Editor can be controlled by remote hosts that wrap the editor with
3+
* an iframe or in some kind of webview.
4+
*/
5+
'use strict';
6+
7+
/**
8+
* @returns An object with the fs wrapper.
9+
*/
10+
var EditorController = function() {
11+
var _returnObj = {};
12+
13+
var _editorActions = null;
14+
var _msgEventListener = null;
15+
var _controllerHost = null;
16+
17+
/** Constants used for iframe messaging */
18+
var CONTROLLER_MESSAGING = Object.freeze({
19+
// Embed editor host type
20+
type: 'pyeditor',
21+
// Embed editor messaging actions
22+
actions: {
23+
// Editor sends it to sync with controller and possibly receive a
24+
// project to load
25+
// direction: Bidirectional
26+
// dataOut: Nothing
27+
// dataIn: projects - An array with python code, editor loads [0]
28+
workspacesync: 'workspacesync',
29+
// Notifies controller 'workspacesync' was successful
30+
// direction: Output
31+
// dataOut: Nothing
32+
workspaceloaded: 'workspaceloaded',
33+
// Sends the editor code to the controller, configured to do this
34+
// periodically
35+
// direction: Output
36+
// dataOut: project - A string with the editor code
37+
workspacesave: 'workspacesave',
38+
// Controller sends code to load into the editor
39+
// direction: Input
40+
// dataIn: project - A string with python code
41+
importproject: 'importproject',
42+
// Controller sends a hex file to load into the editor
43+
// direction: Input
44+
// dataIn: filename - String with the hex file name
45+
// filestring - String with the hex contents
46+
loadhex: 'loadhex',
47+
// Controller sends a python file to load into the editor
48+
// direction: Input
49+
// dataIn: filename - String with the python file name
50+
// filestring - String with the python code from the file
51+
loadfile: 'loadfile',
52+
// Editor sends a python file to the controller
53+
// direction: Output
54+
// dataOut: filename - String with the python file name
55+
// filestring - String with the python code from the file
56+
savefile: 'savefile',
57+
// Editor sends a hex file to the controller
58+
// direction: Output
59+
// dataOut: filename - String with the hex file name
60+
// filestring - String with the python code from the file
61+
flashhex: 'flashhex',
62+
// Change the editor configuration for the mobile apps UX
63+
// The serial and connect buttons are removed, flash button added,
64+
// and the download and flash buttons send data to the controller
65+
// direction: Input
66+
// dataIn: Nothing
67+
mobilemode: 'mobilemode',
68+
}
69+
});
70+
71+
/**
72+
* JS debounce for a given amount of time. If the same function is called
73+
* before the timeout the timer resets.
74+
*
75+
* @param {function} callback - Function to debounce.
76+
* @param {number} wait - Time to wait without calling this debounce to
77+
* finally execute the callback.
78+
*/
79+
function debounce(callback, wait) {
80+
var timeout = null;
81+
return function() {
82+
var args = arguments;
83+
var next = function() {
84+
return callback.apply(this, args);
85+
};
86+
clearTimeout(timeout);
87+
timeout = setTimeout(next, wait);
88+
}
89+
}
90+
91+
/**
92+
* Sending a postMessage to the host controller.
93+
*/
94+
function hostPostMessage(message, targetOrigin) {
95+
if (_controllerHost) {
96+
_controllerHost.postMessage(message, targetOrigin);
97+
} else {
98+
console.error('Trying to postMessage to undefined host controller:');
99+
console.error(message, targetOrigin);
100+
}
101+
}
102+
103+
/**
104+
* Send data to the host controller to save a file into the device.
105+
*
106+
* @param {string} filename - File name for the file to save to the device.
107+
* @param {string} fileStr - File content to save to the device.
108+
*/
109+
function hostSaveFile(filename, fileStr) {
110+
hostPostMessage({
111+
type: CONTROLLER_MESSAGING.type,
112+
action: CONTROLLER_MESSAGING.actions.savefile,
113+
filename: filename,
114+
filestring: fileStr,
115+
}, '*');
116+
}
117+
118+
/**
119+
* Send a hex to the host controller to flash the device.
120+
*
121+
* @param {string} filename - File name for the hex to flash into the device.
122+
* @param {string} hexStr - Hex string to flash to the device.
123+
*/
124+
function hostFlashHex(filename, hexStr) {
125+
hostPostMessage({
126+
type: CONTROLLER_MESSAGING.type,
127+
action: CONTROLLER_MESSAGING.actions.flashhex,
128+
filename: filename,
129+
filestring: hexStr,
130+
}, '*');
131+
}
132+
133+
/**
134+
* Set up the Editor Controller actions required by the protocol messages.
135+
* This does not set up the
136+
*
137+
* @param {object} editorActions - Functions needed to control the editor:
138+
* - setCode(code) - Replace the code in the editor.
139+
* code - String with the code to add to the editor.
140+
* - getCode() - Retrieve the code from the editor.
141+
* - onCodeChange(callback) - Callback to run on every call change.
142+
* callback - Callback function.
143+
* - loadHex(filename, hexStr)
144+
* Sending a hex into the editor to load it.
145+
* filename - String with the file name
146+
* hexStr - String with the hex data
147+
* - loadFileToFs(filename, fileStr)
148+
* Sending a file to the editor to add it to the filesystem.
149+
* filename - String with the file name
150+
* fileStr - String with the python file text
151+
* - setMobileEditor(appFlash, appSave)
152+
* Set up the editor in a special UX mode for the mobile apps.
153+
* appFlash(filename, hexStr) - callback to send hex for flashing
154+
* appSave -
155+
*/
156+
_returnObj.setup = function(editorActions) {
157+
_editorActions = editorActions;
158+
_msgEventListener = function(event) {
159+
if (!event.data) return;
160+
161+
if (event.data.type === CONTROLLER_MESSAGING.type) {
162+
switch (event.data.action) {
163+
// Parent is sending code to update editor
164+
case CONTROLLER_MESSAGING.actions.importproject:
165+
if (!event.data.project || typeof event.data.project !== 'string') {
166+
throw new Error("Invalid 'project' data type. String should be provided.");
167+
}
168+
_editorActions.setCode(event.data.project);
169+
break;
170+
171+
// Parent is sending initial code for editor
172+
// Also here we can sync parent data with editor's data
173+
case CONTROLLER_MESSAGING.actions.workspacesync:
174+
if (!event.data.projects || !Array.isArray(event.data.projects)) {
175+
throw new Error("Invalid 'projects' data type. Array should be provided.");
176+
}
177+
if (event.data.projects.length < 1) {
178+
throw new Error("'projects' array should contain at least one item.");
179+
}
180+
_editorActions.setCode(event.data.projects[0]);
181+
// Notify parent about editor successfully configured
182+
window.parent.postMessage({
183+
type: CONTROLLER_MESSAGING.type,
184+
action: CONTROLLER_MESSAGING.actions.workspaceloaded
185+
}, '*');
186+
break;
187+
188+
// Parent is sending HEX file
189+
case CONTROLLER_MESSAGING.actions.loadhex:
190+
if (!event.data.filename || typeof event.data.filename !== 'string') {
191+
throw new Error("Invalid 'filename' data type. String should be provided.");
192+
}
193+
if (!event.data.filestring || typeof event.data.filestring !== 'string') {
194+
throw new Error("Invalid 'filename' data type. String should be provided.");
195+
}
196+
_editorActions.loadHex(event.data.filename, event.data.filestring);
197+
break;
198+
199+
// Parent is sending file for filesystem
200+
case CONTROLLER_MESSAGING.actions.loadfile:
201+
if (!event.data.filename || typeof event.data.filename !== 'string') {
202+
throw new Error("Invalid 'filename' data type. String should be provided.");
203+
}
204+
if (!event.data.filestring || typeof event.data.filestring !== 'string') {
205+
throw new Error("Invalid 'filestring' data type. String should be provided.");
206+
}
207+
_editorActions.loadFileToFs(event.data.filename, event.data.filestring);
208+
break;
209+
210+
// Parent is requesting postMessage downloads
211+
case CONTROLLER_MESSAGING.actions.mobilemode:
212+
_editorActions.setMobileEditor(hostFlashHex, hostSaveFile);
213+
break;
214+
215+
default:
216+
throw new Error('Unsupported action.')
217+
}
218+
}
219+
};
220+
};
221+
222+
/**
223+
* Initialises the controller based on the URL query string parameters and
224+
* the `window` environment.
225+
* The Classroom controller will be an iframe parent, and the mobile apps
226+
* will have postMessage handlers on different namespaces within `window`.
227+
*
228+
* @param {object} qs - The editor URL query string parameters.
229+
*/
230+
_returnObj.initialise = function(qs) {
231+
var inIframe = window !== window.parent;
232+
var iframeControllerMode = inIframe && qs.controller == '1';
233+
var appControllerMode = qs.mobileApp == '1';
234+
235+
if (iframeControllerMode || appControllerMode) {
236+
// Detect the host controller to send our messages
237+
if (iframeControllerMode && window.parent && window.parent.postMessage) {
238+
// Classroom wraps the editor in an iframe
239+
_controllerHost = window.parent;
240+
} else if (appControllerMode &&
241+
window.webkit &&
242+
window.webkit.messageHandlers &&
243+
window.webkit.messageHandlers.host &&
244+
window.webkit.messageHandlers.host.postMessage) {
245+
// iOS app, 'host' used to match the MakeCode messageHandler name
246+
_controllerHost = window.webkit.messageHandlers.host;
247+
} else if (appControllerMode && window.host && window.host.postMessage) {
248+
// Android app
249+
_controllerHost = window.host
250+
} else {
251+
console.error('Cannot detect valid host controller.');
252+
return;
253+
}
254+
255+
console.log('Activating editor controller mode.');
256+
if (_msgEventListener) {
257+
window.addEventListener('message', _msgEventListener, false);
258+
} else {
259+
throw new Error("The editor controller setup() has not been configured.");
260+
}
261+
window.addEventListener('load', function() {
262+
hostPostMessage({
263+
type: CONTROLLER_MESSAGING.type,
264+
action: CONTROLLER_MESSAGING.actions.workspacesync
265+
}, '*');
266+
});
267+
}
268+
269+
if (iframeControllerMode) {
270+
console.log('Configuring iframe controller.');
271+
// For classroom we clear the code in the editor
272+
_editorActions.setCode(' ');
273+
// Send code to the controller in real time (with a 1s debounce)
274+
var debounceCodeChange = debounce(function(code) {
275+
hostPostMessage({
276+
type: CONTROLLER_MESSAGING.type,
277+
action: CONTROLLER_MESSAGING.actions.workspacesave,
278+
project: code
279+
}, '*');
280+
}, 1000);
281+
_editorActions.onCodeChange(function() {
282+
debounceCodeChange(_editorActions.getCode());
283+
});
284+
}
285+
};
286+
287+
return _returnObj;
288+
}
289+
290+
if (typeof module !== 'undefined' && module.exports) {
291+
global.EditorController = EditorController;
292+
} else {
293+
window.EditorController = EditorController;
294+
}

0 commit comments

Comments
 (0)