forked from vercel/hyper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugins.js
514 lines (434 loc) · 13.7 KB
/
plugins.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
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
import {remote} from 'electron';
import {connect as reduxConnect} from 'react-redux';
import {basename} from 'path';
// patching Module._load
// so plugins can `require` them without needing their own version
// https://github.com/zeit/hyper/issues/619
import React, {PureComponent} from 'react';
import ReactDOM from 'react-dom';
import Notification from '../components/notification';
import notify from './notify';
//eslint-disable-next-line import/newline-after-import
const Module = require('module');
const originalLoad = Module._load;
Module._load = function _load(path) {
// PLEASE NOTE: Code changes here, also need to be changed in
// app/plugins.js
switch (path) {
case 'react':
return React;
case 'react-dom':
return ReactDOM;
case 'hyper/component':
return PureComponent;
case 'hyper/notify':
return notify;
case 'hyper/Notification':
return Notification;
case 'hyper/decorate':
return decorate;
default:
return originalLoad.apply(this, arguments);
}
};
// remote interface to `../plugins`
const plugins = remote.require('./plugins');
// `require`d modules
let modules;
// cache of decorated components
let decorated = {};
// various caches extracted of the plugin methods
let connectors;
let middlewares;
let uiReducers;
let sessionsReducers;
let termGroupsReducers;
let tabPropsDecorators;
let tabsPropsDecorators;
let termPropsDecorators;
let termGroupPropsDecorators;
let propsDecorators;
let reducersDecorators;
const clearModulesCache = () => {
// the fs locations where user plugins are stored
const {path, localPath} = plugins.getBasePaths();
// trigger unload hooks
modules.forEach(mod => {
if (mod.onRendererUnload) {
mod.onRendererUnload(window);
}
});
// clear require cache
for (const entry in window.require.cache) {
if (entry.indexOf(path) === 0 || entry.indexOf(localPath) === 0) {
// `require` is webpacks', `window.require` is electron's
delete window.require.cache[entry];
}
}
};
const pathModule = window.require('path');
const getPluginName = path => pathModule.basename(path);
const getPluginVersion = path => {
let version = null;
try {
version = window.require(pathModule.resolve(path, 'package.json')).version;
} catch (err) {
//eslint-disable-next-line no-console
console.warn(`No package.json found in ${path}`);
}
return version;
};
const loadModules = () => {
//eslint-disable-next-line no-console
console.log('(re)loading renderer plugins');
const paths = plugins.getPaths();
// initialize cache that we populate with extension methods
connectors = {
Terms: {state: [], dispatch: []},
Header: {state: [], dispatch: []},
Hyper: {state: [], dispatch: []},
Notifications: {state: [], dispatch: []}
};
uiReducers = [];
middlewares = [];
sessionsReducers = [];
termGroupsReducers = [];
tabPropsDecorators = [];
tabsPropsDecorators = [];
termPropsDecorators = [];
termGroupPropsDecorators = [];
propsDecorators = {
getTermProps: termPropsDecorators,
getTabProps: tabPropsDecorators,
getTabsProps: tabsPropsDecorators,
getTermGroupProps: termGroupPropsDecorators
};
reducersDecorators = {
reduceUI: uiReducers,
reduceSessions: sessionsReducers,
reduceTermGroups: termGroupsReducers
};
const loadedPlugins = plugins.getLoadedPluginVersions().map(plugin => plugin.name);
modules = paths.plugins
.concat(paths.localPlugins)
.filter(plugin => loadedPlugins.indexOf(basename(plugin)) !== -1)
.map(path => {
let mod;
const pluginName = getPluginName(path);
const pluginVersion = getPluginVersion(path);
// window.require allows us to ensure this doesn't get
// in the way of our build
try {
mod = window.require(path);
} catch (err) {
notify(
'Plugin load error',
`"${pluginName}" failed to load in the renderer process. Check Developer Tools for details.`,
{error: err}
);
return undefined;
}
for (const i in mod) {
if ({}.hasOwnProperty.call(mod, i)) {
mod[i]._pluginName = pluginName;
mod[i]._pluginVersion = pluginVersion;
}
}
// mapHyperTermState mapping for backwards compatibility with hyperterm
if (mod.mapHyperTermState) {
mod.mapHyperState = mod.mapHyperTermState;
//eslint-disable-next-line no-console
console.error('mapHyperTermState is deprecated. Use mapHyperState instead.');
}
// mapHyperTermDispatch mapping for backwards compatibility with hyperterm
if (mod.mapHyperTermDispatch) {
mod.mapHyperDispatch = mod.mapHyperTermDispatch;
//eslint-disable-next-line no-console
console.error('mapHyperTermDispatch is deprecated. Use mapHyperDispatch instead.');
}
if (mod.middleware) {
middlewares.push(mod.middleware);
}
if (mod.reduceUI) {
uiReducers.push(mod.reduceUI);
}
if (mod.reduceSessions) {
sessionsReducers.push(mod.reduceSessions);
}
if (mod.reduceTermGroups) {
termGroupsReducers.push(mod.reduceTermGroups);
}
if (mod.mapTermsState) {
connectors.Terms.state.push(mod.mapTermsState);
}
if (mod.mapTermsDispatch) {
connectors.Terms.dispatch.push(mod.mapTermsDispatch);
}
if (mod.mapHeaderState) {
connectors.Header.state.push(mod.mapHeaderState);
}
if (mod.mapHeaderDispatch) {
connectors.Header.dispatch.push(mod.mapHeaderDispatch);
}
if (mod.mapHyperState) {
connectors.Hyper.state.push(mod.mapHyperState);
}
if (mod.mapHyperDispatch) {
connectors.Hyper.dispatch.push(mod.mapHyperDispatch);
}
if (mod.mapNotificationsState) {
connectors.Notifications.state.push(mod.mapNotificationsState);
}
if (mod.mapNotificationsDispatch) {
connectors.Notifications.dispatch.push(mod.mapNotificationsDispatch);
}
if (mod.getTermGroupProps) {
termGroupPropsDecorators.push(mod.getTermGroupProps);
}
if (mod.getTermProps) {
termPropsDecorators.push(mod.getTermProps);
}
if (mod.getTabProps) {
tabPropsDecorators.push(mod.getTabProps);
}
if (mod.getTabsProps) {
tabsPropsDecorators.push(mod.getTabsProps);
}
if (mod.onRendererWindow) {
mod.onRendererWindow(window);
}
//eslint-disable-next-line no-console
console.log(`Plugin ${pluginName} (${pluginVersion}) loaded.`);
return mod;
})
.filter(mod => Boolean(mod));
const deprecatedPlugins = plugins.getDeprecatedConfig();
Object.keys(deprecatedPlugins).forEach(name => {
const {css} = deprecatedPlugins[name];
if (css) {
//eslint-disable-next-line no-console
console.warn(`Warning: "${name}" plugin uses some deprecated CSS classes (${css.join(', ')}).`);
}
});
};
// load modules for initial decoration
loadModules();
export function reload() {
clearModulesCache();
loadModules();
// trigger re-decoration when components
// get re-rendered
decorated = {};
}
function getProps(name, props, ...fnArgs) {
const decorators = propsDecorators[name];
let props_;
decorators.forEach(fn => {
let ret_;
if (!props_) {
props_ = Object.assign({}, props);
}
try {
ret_ = fn(...fnArgs, props_);
} catch (err) {
notify('Plugin error', `${fn._pluginName}: Error occurred in \`${name}\`. Check Developer Tools for details.`, {
error: err
});
return;
}
if (!ret_ || typeof ret_ !== 'object') {
notify('Plugin error', `${fn._pluginName}: Invalid return value of \`${name}\` (object expected).`);
return;
}
props_ = ret_;
});
return props_ || props;
}
export function getTermGroupProps(uid, parentProps, props) {
return getProps('getTermGroupProps', props, uid, parentProps);
}
export function getTermProps(uid, parentProps, props) {
return getProps('getTermProps', props, uid, parentProps);
}
export function getTabsProps(parentProps, props) {
return getProps('getTabsProps', props, parentProps);
}
export function getTabProps(tab, parentProps, props) {
return getProps('getTabProps', props, tab, parentProps);
}
// connects + decorates a class
// plugins can override mapToState, dispatchToProps
// and the class gets decorated (proxied)
export function connect(stateFn, dispatchFn, c, d = {}) {
return (Class, name) => {
return reduxConnect(
state => {
let ret = stateFn(state);
connectors[name].state.forEach(fn => {
let ret_;
try {
ret_ = fn(state, ret);
} catch (err) {
notify(
'Plugin error',
`${fn._pluginName}: Error occurred in \`map${name}State\`. Check Developer Tools for details.`,
{error: err}
);
return;
}
if (!ret_ || typeof ret_ !== 'object') {
notify('Plugin error', `${fn._pluginName}: Invalid return value of \`map${name}State\` (object expected).`);
return;
}
ret = ret_;
});
return ret;
},
dispatch => {
let ret = dispatchFn(dispatch);
connectors[name].dispatch.forEach(fn => {
let ret_;
try {
ret_ = fn(dispatch, ret);
} catch (err) {
notify(
'Plugin error',
`${fn._pluginName}: Error occurred in \`map${name}Dispatch\`. Check Developer Tools for details.`,
{error: err}
);
return;
}
if (!ret_ || typeof ret_ !== 'object') {
notify(
'Plugin error',
`${fn._pluginName}: Invalid return value of \`map${name}Dispatch\` (object expected).`
);
return;
}
ret = ret_;
});
return ret;
},
c,
d
)(decorate(Class, name));
};
}
function decorateReducer(name, fn) {
const reducers = reducersDecorators[name];
return (state, action) => {
let state_ = fn(state, action);
reducers.forEach(pluginReducer => {
let state__;
try {
state__ = pluginReducer(state_, action);
} catch (err) {
notify('Plugin error', `${fn._pluginName}: Error occurred in \`${name}\`. Check Developer Tools for details.`, {
error: err
});
return;
}
if (!state__ || typeof state__ !== 'object') {
notify('Plugin error', `${fn._pluginName}: Invalid return value of \`${name}\`.`);
return;
}
state_ = state__;
});
return state_;
};
}
export function decorateTermGroupsReducer(fn) {
return decorateReducer('reduceTermGroups', fn);
}
export function decorateUIReducer(fn) {
return decorateReducer('reduceUI', fn);
}
export function decorateSessionsReducer(fn) {
return decorateReducer('reduceSessions', fn);
}
// redux middleware generator
export const middleware = store => next => action => {
const nextMiddleware = remaining => action_ =>
remaining.length ? remaining[0](store)(nextMiddleware(remaining.slice(1)))(action_) : next(action_);
nextMiddleware(middlewares)(action);
};
// expose decorated component instance to the higher-order components
function exposeDecorated(Component_) {
return class DecoratedComponent extends React.Component {
constructor(props, context) {
super(props, context);
this.onRef = this.onRef.bind(this);
}
onRef(decorated_) {
if (this.props.onDecorated) {
try {
this.props.onDecorated(decorated_);
} catch (e) {
notify('Plugin error', `Error occurred. Check Developer Tools for details`, {error: e});
}
}
}
render() {
return React.createElement(Component_, Object.assign({}, this.props, {ref: this.onRef}));
}
};
}
function getDecorated(parent, name) {
if (!decorated[name]) {
let class_ = exposeDecorated(parent);
class_.displayName = `_exposeDecorated(${name})`;
modules.forEach(mod => {
const method = 'decorate' + name;
const fn = mod[method];
if (fn) {
let class__;
try {
class__ = fn(class_, {React, PureComponent, Notification, notify});
class__.displayName = `${fn._pluginName}(${name})`;
} catch (err) {
notify(
'Plugin error',
`${fn._pluginName}: Error occurred in \`${method}\`. Check Developer Tools for details`,
{error: err}
);
return;
}
if (!class__ || typeof class__.prototype.render !== 'function') {
notify(
'Plugin error',
`${
fn._pluginName
}: Invalid return value of \`${method}\`. No \`render\` method found. Please return a \`React.Component\`.`
);
return;
}
class_ = class__;
}
});
decorated[name] = class_;
}
return decorated[name];
}
// for each component, we return a higher-order component
// that wraps with the higher-order components
// exposed by plugins
export function decorate(Component_, name) {
return class DecoratedComponent extends React.Component {
constructor(props) {
super(props);
this.state = {hasError: false};
}
componentDidCatch() {
this.setState({hasError: true});
// No need to detail this error because React print those informations.
notify(
'Plugin error',
`Plugins decorating ${name} has been disabled because of a plugin crash. Check Developer Tools for details.`
);
}
render() {
const Sub = this.state.hasError ? Component_ : getDecorated(Component_, name);
return React.createElement(Sub, this.props);
}
};
}