-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
example.mjs
327 lines (303 loc) · 11.6 KB
/
example.mjs
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import { withRouter } from 'react-router-dom';
import examples from './helpers/example-data.mjs';
import { MIN_DESKTOP_WIDTH } from './constants.mjs';
import { iframePath } from '../assetPath.mjs';
import { DeviceSelector } from './device-selector.mjs';
import { ErrorBoundary } from './error-boundary.mjs';
import { jsx, fragment } from './jsx.mjs';
import { Panel, Container, Button, Spinner } from '@playcanvas/pcui/react';
import React, { Component } from 'react';
import MonacoEditor from "@monaco-editor/react";
import { iframeReady, iframeReload, iframeRequestFiles } from './iframeUtils.mjs';
import { getOrientation } from './utils.mjs';
import * as PCUI from '@playcanvas/pcui';
import * as ReactPCUI from '@playcanvas/pcui/react';
/**
* @typedef {object} ControlOptions
* @property {import('@playcanvas/observer').Observer} observer - The observer.
* @property {import('@playcanvas/pcui')} PCUI - The PCUI vanilla module.
* @property {import('@playcanvas/pcui/react')} ReactPCUI - The PCUI React module.
* @property {import('react')} React - The PCUI React module.
* @property {import('./jsx.mjs').jsx} jsx - Shortcut for creating a React JSX Element.
* @property {import('./jsx.mjs').fragment} fragment - Shortcut for creating a React JSX fragment.
*/
/**
* @typedef {object} Props
* @property {{params: {category: string, example: string}}} match
*/
/**
* @typedef {object} State
* @property {'portrait' | 'landscape'} orientation - The orientation.
* @property {boolean} collapsed - Collapsed or not.
* @property {boolean} exampleLoaded - Example is loaded or not.
* @property {Function} controls - Controls function from example.
* @property {'code' | 'parameters'} show - Used in case of mobile view.
* @property {Record<string, string>} files - Files of example (controls, shaders, example itself)
*/
/** @type {typeof Component<Props, State>} */
const TypedComponent = Component;
class Example extends TypedComponent {
/** @type {State} */
state = {
orientation: getOrientation(),
collapsed: window.top.innerWidth < MIN_DESKTOP_WIDTH,
exampleLoaded: false,
//controls: () => jsx('pre', null, 'Status: initial'),
controls: () => undefined,
show: 'code',
files: {'example.mjs': '// loading'}
};
/**
* @param {Partial<State>} state - The partial state to update.
*/
mergeState(state) {
// new state is always calculated from the current state,
// avoiding any potential issues with asynchronous updates
this.setState(prevState => ({ ...prevState, ...state }));
}
/**
* Called for resizing and changing orientation of device.
*/
onLayoutChange() {
this.mergeState({ orientation: getOrientation() });
}
onExampleLoading() {
this.mergeState({
exampleLoaded: false,
//controls: () => jsx('h1', null, 'state: reload'),
controls: null,
});
}
onExampleLoad(event) {
/** @type {Record<string, string>} */
const files = event.files;
const controlsSrc = files['controls.mjs'];
if (controlsSrc) {
let controls;
try {
controls = Function('return ' + controlsSrc)();
} catch (e) {
controls = () => jsx('pre', null, 'error: ' + e.toString());
}
this.mergeState({
exampleLoaded: true,
controls,
files,
});
// console.log("controlsSrc", controlsSrc);
} else {
// When switching examples from one with controls to one without controls...
this.mergeState({
exampleLoaded: true,
controls: null,
files,
});
}
}
onUpdateFiles(event) {
const files = event.detail.files;
// console.log("updateFiles", files);
const controlsSrc = files['controls.mjs'] ?? 'null';
if (!files['controls.mjs']) {
this.mergeState({
exampleLoaded: true,
controls: null,
});
}
let controls;
try {
controls = Function('return ' + controlsSrc)();
} catch (e) {
controls = () => jsx('pre', null, e.toString());
}
this.mergeState({
exampleLoaded: true,
controls,
});
}
componentDidMount() {
// PCUI should just have a "onHeaderClick" but can't find anything
const controlPanel = document.getElementById("controlPanel");
const controlPanelHeader = controlPanel.querySelector('.pcui-panel-header');
controlPanelHeader.onclick = () => this.toggleCollapse();
// Other events
this.handleRequestedFiles = this.handleRequestedFiles.bind(this);
this.onLayoutChange = this.onLayoutChange.bind(this);
this.onExampleLoading = this.onExampleLoading.bind(this);
this.onExampleLoad = this.onExampleLoad.bind(this);
this.onUpdateFiles = this.onUpdateFiles.bind(this);
window.addEventListener("requestedFiles", this.handleRequestedFiles);
window.addEventListener("resize", this.onLayoutChange);
window.addEventListener("orientationchange", this.onLayoutChange);
window.addEventListener('exampleLoading', this.onExampleLoading);
window.addEventListener('exampleLoad', this.onExampleLoad);
window.addEventListener('updateFiles', this.onUpdateFiles);
iframeRequestFiles();
}
componentWillUnmount() {
window.removeEventListener("requestedFiles", this.handleRequestedFiles);
window.removeEventListener("resize", this.onLayoutChange);
window.removeEventListener("orientationchange", this.onLayoutChange);
window.removeEventListener('exampleLoading', this.onExampleLoading);
window.removeEventListener('exampleLoad', this.onExampleLoad);
window.removeEventListener('updateFiles', this.onUpdateFiles);
}
get path() {
return `/${this.props.match.params.category}/${this.props.match.params.example}`;
}
get iframePath() {
const example = examples.paths[this.path];
return `${iframePath}/${example.category}_${example.name}.html`;
// todo: Complete standalone ES6 version, currently ignored, because focus is on MVP
// return `${iframePath}/index.html?category=${example.category}&example=${example.name}`;
}
renderDeviceSelector() {
return jsx(DeviceSelector, {
onSelect: iframeReload, // reload the iframe after updating the device
});
}
renderControls() {
const { exampleLoaded, controls } = this.state;
const ready = exampleLoaded && controls && iframeReady();
if (!ready) {
return;
}
return jsx(
ErrorBoundary,
null,
jsx(this.state.controls, {
observer: window.observerData,
PCUI,
ReactPCUI,
React,
jsx,
fragment,
}),
);
}
/**
* Not the nicest way to fetch UI state from a CSS class, but we are
* lacking a onHeaderClick panel callback which could hand us the state.
* This is still better than:
* 1) Hoping that the toggle functionality just happens to be calibrated
* to the on/off toggling.
* 2) Setting "collapsed" state everywhere via informed guesses.
*/
get collapsed() {
const controlPanel = document.getElementById("controlPanel");
const collapsed = controlPanel.classList.contains("pcui-collapsed");
return collapsed;
}
toggleCollapse() {
this.mergeState({ collapsed: !this.collapsed });
//console.log("Example#toggleCollapse> was ", collapsed);
}
handleRequestedFiles(event) {
// console.log('Example#handleRequestedFiles, files: ', event.detail);
const files = event.detail;
this.mergeState({ files });
}
renderPortrait() {
const { collapsed, controls, show, files } = this.state;
return jsx(Panel,
{
id: 'controlPanel',
class: ['mobile'],
resizable: 'top',
headerText: 'CODE & CONTROLS',
collapsible: true,
collapsed,
//header: jsx('h1', null, "data header"),
//onClick: this.toggleCollapse.bind(this),
//onExpand: this.toggleCollapse.bind(this),
},
// jsx('button', null, "Example#renderPortrait()"),
this.renderDeviceSelector(),
//this.renderControls(),
jsx(
Container,
{
id: 'controls-wrapper',
class: controls ? 'has-controls' : null
},
jsx(
Container,
{
id: 'controlPanel-tabs',
class: 'tabs-container'
},
jsx(Button, {
text: 'CODE',
id: 'codeButton',
class: show === 'code' ? 'selected' : null,
onClick: () => this.mergeState({ show: 'code' })
}),
jsx(Button, {
text: 'PARAMETERS',
class: show === 'parameters' ? 'selected' : null,
id: 'paramButton',
onClick: () => this.mergeState({ show: 'parameters' })
}),
),
// jsx('button', {onClick: () => console.log(this.state)}, "Example#renderPortrait"),
show === 'parameters' && jsx(
Container,
{
id: 'controlPanel-controls'
},
this.renderControls(),
),
show === 'code' && jsx(
MonacoEditor,
{
options: {
readOnly: true,
theme: 'vs-dark',
},
defaultLanguage: "javascript",
value: files['example.mjs'],
}
)
)
);
}
renderLandscape() {
const { collapsed } = this.state;
return fragment(
jsx(Panel,
{
id: 'controlPanel',
class: ['landscape'],
resizable: 'top',
headerText: 'CONTROLS',
collapsible: true,
collapsed,
},
// jsx('button', {onClick: () => console.log(this.state)}, "Example#renderLandscape"),
this.renderDeviceSelector(),
this.renderControls(),
)
);
}
render() {
const { iframePath } = this;
const { orientation, exampleLoaded } = this.state;
// console.log("Example#render", JSON.stringify(this.state, null, 2));
return jsx(Container,
{
id: "canvas-container"
},
!exampleLoaded && jsx(Spinner, { size: 50 }),
jsx("iframe", {
id: "exampleIframe",
key: iframePath,
src: iframePath
}),
orientation === 'portrait' ? this.renderPortrait() : this.renderLandscape(),
);
}
}
const ExamptWithRouter = withRouter(Example);
export {
ExamptWithRouter as Example
};