-
Notifications
You must be signed in to change notification settings - Fork 156
/
api.js
253 lines (214 loc) · 7.06 KB
/
api.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
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
/**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import '../polyfill/event-target.js';
import * as channel from '../lib/channel.js';
import {resolvable} from '../lib/promises.js';
import {read} from '../lib/params.js';
import {globalClickHandler} from '../core/router.js';
import {scope} from './route.js';
import {dashCamelCase} from '../lib/case.js';
import * as common from '../core/common.js';
/**
* On creation, configure frame connecting to parent. This announces preload events (which can
* happen after preload actually "completes").
*/
const sceneApi = (function() {
const params = read(window.location.search);
const handlers = [];
const {talkback, ready} = (function() {
if (!channel.withinFrame) {
return {
talkback() {},
ready: Promise.resolve(params), // use params as data for testing
};
}
let data = null;
const r = resolvable();
const talkback = channel.parent(({type, payload}) => {
switch (type) {
case 'data':
data = payload; // save here but allow handlers to run, for initial payload
break;
case 'ready':
return r.resolve(data || {});
}
handlers.some((handler) => handler(type, payload));
});
return {talkback, ready: r.promise};
}());
// Configure preload, which reports +ve tasks (work to do) and -ve updates (work done).
const resolveTask = () => talkback({type: 'tasks', payload: -1});
window.addEventListener(common.preloadEvent, (ev) => {
const tasks = /** @type {!Array<!Promise>} */ (ev.detail);
talkback({type: 'tasks', payload: tasks.length});
tasks.forEach((t) => t.catch(() => null).then(resolveTask));
});
// Just let the parent there's sounds to preload. This is ignored by the fallback host.
window.addEventListener(common.internalSoundPreload, (ev) => {
talkback({type: 'sounds', payload: ev.detail});
});
// Create shared default exported object. Used by scenes.
const target = new (class extends EventTarget {
constructor() {
super();
this._config = undefined;
}
get preload() {
return common.preload;
}
/**
* Returns the value of a param passed to this frame. Used for route.
*
* @param {string} key to return
* @return {string}
*/
param(key) {
return params[key] || '';
}
config(data = {}) {
this._config = data;
}
_bufferList(type, ...args) {
this._buffer(type, args);
}
_buffer(type, payload) {
this.ready(() => talkback({type, payload}));
}
/**
* Call a method when the scene is ready to load.
*/
ready(fn) {
return ready.then(fn);
}
});
// Push general event handler. This handles control from parent frame and dispatches events on
// API, which is an EventTarget.
handlers.push((type, payload) => {
switch (type) {
case 'data':
target.dispatchEvent(new CustomEvent('data', {detail: payload}));
return true;
case 'pause':
case 'resume':
case 'restart':
case 'muted':
case 'unmuted':
target.dispatchEvent(new Event(type));
return true;
case 'deviceorientation':
case 'keyup':
case 'keydown':
// TODO(samthor): This also sends us 'repeat' events, and mixes badly (?) with keyboard
// inputs. It might be worth merging them, but only if a game isn't explicitly multiplayer.
const event = new CustomEvent(type, {bubbles: true});
Object.assign(event, payload);
document.dispatchEvent(event);
return true;
}
});
// Announce the config after a short leeway (this is longer than a microtask, as `Promise.resolve`
// is used to kick off the first tasks).
window.setTimeout(() => {
talkback({type: 'config', payload: target._config || {}});
target.config = () => {
throw new TypeError('config() cannot be called after first tick');
};
target._config = undefined;
}, 100);
// Add generic helpers to the API object, used by scenes. If true, accepts any number of params
// which are passed as an Array. If false, just sends a single argument.
const bufferNames = {
'tutorialQueue': true,
'tutorialDismiss': true,
'focusOnMenu': true,
'gtag': true,
'play': true,
'data': false,
'score': false,
'gameover': false,
'go': false,
'error': false,
};
for (const key in bufferNames) {
const listType = bufferNames[key];
const method = listType ? target._bufferList : target._buffer;
const type = dashCamelCase(key); // 'tutorialQueue' becomes 'tutorial-queue'
target[key] = method.bind(target, type);
}
// Add global Analytics passthrough.
window.gtag = target.gtag;
// Handle common sound playback code. This is buffered just like `api.play()`.
window.addEventListener(common.playEvent, (ev) => target.play(...ev.detail));
// Handle common routing code.
window.addEventListener(common.goEvent, (ev) => target.go(ev.detail));
// Force at least one preload task.
common.preload.wait(Promise.resolve());
return target;
}());
/**
* Installs `santaApp` global handler.
*/
function buildLegacyHandler() {
const sanitizeSoundArgs = (args) => {
if (args.length !== 1) {
return args;
}
const first = args[0];
if (first.name && first.args && first.args instanceof Array) {
// fix "{name: 'foo', args: []}" case
args = [first.name, ...first.args];
}
return args;
};
const fire = (eventName, ...args) => {
switch (eventName) {
case 'sound-trigger':
case 'sound-ambient':
args = sanitizeSoundArgs(args);
sceneApi.play(...args);
break;
case 'game-data':
sceneApi.data(args[0] || null);
break;
case 'game-score':
sceneApi.score(args[0] || {});
break;
case 'game-stop':
sceneApi.gameover(args[0] || {});
break;
case 'tutorial-queue':
sceneApi.tutorialQueue(...(args[0] || []));
break;
case 'tutorial-dismiss':
sceneApi.tutorialDismiss(...(args[0] || []));
break;
default:
console.debug('unhandled santaApi.fire', eventName);
}
}
return {
fire,
get headerSize() {
// leftover from old (2017-era) design, with a fixed height header
return 0;
},
};
}
window.santaApp = buildLegacyHandler();
// Install global click handler, for primary page nav.
const handler = globalClickHandler(scope, (sceneName) => sceneApi.go(sceneName));
document.body.addEventListener('click', handler);
export default sceneApi;