This repository has been archived by the owner on Apr 16, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
demo.js
90 lines (73 loc) · 1.88 KB
/
demo.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
const L20nDemo = (function() {
let _getState;
let _connected;
let _registered;
function emit(action, requestId, data) {
document.dispatchEvent(
new CustomEvent('mozL20nDemo', {
bubbles: true,
detail: {
action, requestId, data: data || {},
}
})
);
}
function debounce(fn) {
let timer = null;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), 250);
};
}
function roundtrip(msg, state) {
const reqId = Math.random().toString(36).replace(/[^a-z]+/g, '');
return new Promise((resolve, reject) => {
function onResponse(evt) {
if (evt.detail.requestId === reqId) {
clearTimeout(t);
window.removeEventListener('mozL20nDemoResponse', onResponse);
resolve();
}
}
const t = setTimeout(() => {
window.removeEventListener('mozL20nDemoResponse', onResponse);
reject();
}, 15000);
window.addEventListener('mozL20nDemoResponse', onResponse);
emit(msg, reqId, state);
});
}
function attachEditorHandlers() {
const source = ace.edit("source");
const incr = () => emit('update', null, _getState());
source.getSession().on('change', debounce(incr));
}
function register(state) {
return _connected.then(
() => roundtrip('register', state)
).then(
attachEditorHandlers
);
}
function update(state) {
return roundtrip('update', state);
}
return {
init(getState) {
_getState = getState;
return _connected = roundtrip('helo');
},
register(state) {
_registered = register();
},
update() {
const state = _getState();
if (!state.demo) {
return Promise.reject();
}
return (_registered || this.register(state)).then(
() => update(state)
);
},
};
})();