-
Notifications
You must be signed in to change notification settings - Fork 11
/
rapiop.ts
458 lines (434 loc) · 11.9 KB
/
rapiop.ts
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
import { loadResources } from './lib/load';
import { getProjectKeyFromPath } from './lib/route';
import { createInterceptor } from './lib/interceptor';
import { ErrorType } from './lib/error';
import {
Config,
ProjectConfig,
Option,
ProjectOption,
RegisterConfig,
ProjectRegisterConfig,
InnerShared,
Plugin,
OnError,
AnyFunction
} from './interface';
import Hooks, { Hook } from './Hooks';
/**
* 生命周期函数
*/
const asyncLifeCycleHelper = async ({
hooks,
projectKey,
projectConfig = {},
defaultHandler,
onError,
errorType
}: {
hooks: {
before?: Hook;
main: Hook;
after?: Hook;
};
projectKey: string;
projectConfig?: ProjectConfig;
defaultHandler: AnyFunction;
onError: OnError;
errorType: string;
}): Promise<boolean> => {
hooks.before && hooks.before.call(projectKey);
const interceptor = createInterceptor();
await hooks.main.promise(projectKey, projectConfig, {
intercept: interceptor.intercept,
fail: interceptor.fail
});
let failed = interceptor.getFailed();
const intercepted = interceptor.getIntercepted();
let handlerResult;
if (!failed && !intercepted) {
try {
handlerResult = await defaultHandler();
} catch (e) {
failed = e;
}
}
if (failed) {
const error = new Error(errorType);
console.error(error, ...(failed === true ? [] : [failed]));
onError(error);
return false;
}
hooks.after && hooks.after.call(projectKey);
return handlerResult === false ? false : true;
};
/**
* 挂载项目
*/
const mountProject = async ({
projectKey,
projectRegisterConfig,
mountDOM,
hooks,
onError
}: {
projectKey: string;
projectRegisterConfig: ProjectRegisterConfig;
mountDOM: Element;
hooks: Hooks;
onError: OnError;
}): Promise<boolean> => {
// mountDOM 为空时,不处理
if (!mountDOM) {
// console.info(`mountDOM didn't provided`);
return;
}
// 已经 load 时,触发 mount
const { mount } = projectRegisterConfig;
if (!mount) {
console.error(`mount of project: ${projectKey} not exist`);
return;
}
return await asyncLifeCycleHelper({
hooks: {
before: hooks.beforeMount,
main: hooks.mount,
after: hooks.afterMount
},
projectKey,
defaultHandler: () => mount(mountDOM),
onError,
errorType: ErrorType.MountFailed
});
};
/**
* 卸载项目
*/
const unmountProject = async ({
projectKey,
projectRegisterConfig,
mountDOM,
hooks,
onError
}: {
projectKey: string;
projectRegisterConfig: ProjectRegisterConfig;
mountDOM: Element;
hooks: Hooks;
onError: OnError;
}): Promise<boolean> => {
const { unmount } = projectRegisterConfig;
if (!unmount) {
console.error(`unmount of project: ${projectKey} not exist`);
return;
}
return await asyncLifeCycleHelper({
hooks: {
before: hooks.beforeUnmount,
main: hooks.unmount,
after: hooks.afterUnmount
},
projectKey,
defaultHandler: () => unmount(mountDOM),
onError,
errorType: ErrorType.MountFailed
});
};
/**
* 加载项目资源
*/
const loadProjectResources = async ({
projectKey,
projectConfig = {},
hooks,
onError,
loadResources
}: {
projectKey: string;
projectConfig: ProjectConfig;
hooks: Hooks;
onError: OnError;
loadResources: AnyFunction;
}) => {
const { files } = projectConfig;
if (!files) {
// console.warn(`project ${projectKey} has no file`);
return false;
}
return await asyncLifeCycleHelper({
hooks: {
main: hooks.loadResources
},
projectKey,
projectConfig,
defaultHandler: () => loadResources(projectConfig, onError),
onError,
errorType: ErrorType.LoadResourceFailed
});
};
/**
* 进入项目
*/
const enterProject = async ({
projectKey,
projectConfig = {},
projectRegisterConfig,
mountDOM,
hooks,
onError,
loadResources
}: {
projectKey: string;
projectConfig: ProjectConfig;
projectRegisterConfig: ProjectRegisterConfig;
mountDOM: Element;
hooks: Hooks;
onError: OnError;
loadResources: AnyFunction;
}): Promise<boolean> => {
return await asyncLifeCycleHelper({
hooks: {
main: hooks.enter
},
projectKey,
projectConfig,
defaultHandler: async () => {
// 无配置项认定为项目未加载
if (!projectRegisterConfig) {
loadProjectResources({
projectKey,
projectConfig,
hooks,
onError,
loadResources
});
return false;
}
// 挂载项目
return !!(await mountProject({
projectKey,
projectRegisterConfig,
mountDOM,
hooks,
onError
}));
},
onError,
errorType: ErrorType.EnterFailed
});
};
/**
* 退出项目
*/
const exitProject = async ({
projectKey,
projectRegisterConfig,
mountDOM,
hooks,
onError
}: {
projectKey: string;
projectRegisterConfig: ProjectRegisterConfig;
mountDOM: Element;
hooks: Hooks;
onError: OnError;
}): Promise<boolean> => {
if (projectKey) {
return await asyncLifeCycleHelper({
hooks: {
main: hooks.exit
},
projectKey,
defaultHandler: () =>
unmountProject({
projectKey,
projectRegisterConfig,
mountDOM,
hooks,
onError
}),
onError,
errorType: ErrorType.ExitFailed
});
}
};
/**
* 创建实例
* @param option 实例参数
* @return instance 实例
* @return instance.register 注册一个项目
* @return instance.registerPlugin 注册插件
* @return instance.hooks 钩子
*/
const rapiop = (option: Option) => {
const hooks = new Hooks();
const {
// 插件目录
plugins = [],
// 无匹配项目时的默认项目
fallbackProjectKey = 'home',
// 自定义 history 对象
history,
// 项目挂载节点
mountDOM: initedMountDOM,
// 错误时的回调
onError = () => {},
// 自定义路由匹配的函数
getProjectKeyFromPath: customGetProjectKeyFromPath
} = option;
let {
// 项目路由配置信息,支持函数和 Promise
config
} = option;
if (!config) {
console.error(`Must provide config when init App`);
return;
}
let _config: Config,
lock = false,
queuing = false,
mountedProjectKey: string,
mountDOM: Element;
const registerConfig: RegisterConfig = {};
// 更新项目
const _refresh = async (force?: boolean, forceProjectKey?: string) => {
if (!_config) {
// console.info(`Config is not provided`);
return;
}
const projectKey =
forceProjectKey ||
(customGetProjectKeyFromPath || getProjectKeyFromPath)(location.pathname, _config) ||
fallbackProjectKey;
// 匹配的项目未改变,不处理,force 时强行重新加载
if (!force && mountedProjectKey === projectKey) {
// console.info(`Project ${projectKey} was mounted`);
return;
}
// 卸载现有项目
if (
await exitProject({
projectKey: mountedProjectKey,
projectRegisterConfig: registerConfig[mountedProjectKey],
mountDOM,
hooks,
onError
})
) {
mountedProjectKey = null;
}
// 进入当前项目
if (
await enterProject({
projectKey,
projectConfig: _config[projectKey],
projectRegisterConfig: registerConfig[projectKey],
mountDOM,
hooks,
onError,
loadResources: (projectInfo, onError) => innerShared.loadResources(projectInfo, onError)
})
) {
mountedProjectKey = projectKey;
}
};
const refresh = async (force?: boolean, forceProjectKey?: string) => {
if (lock) {
queuing = true;
return;
}
lock = true;
await _refresh(force, forceProjectKey);
lock = false;
if (queuing) {
queuing = false;
refresh(force);
}
};
const register = (
projectKey: string,
mount: (mountDOM: Element) => void,
unmount: () => void,
option: ProjectOption
) => {
if (registerConfig[projectKey]) {
return console.error(`Project: ${projectKey} was registered`);
}
registerConfig[projectKey] = {
mount,
unmount,
option
};
hooks.afterRegister.call(projectKey);
};
// hooks tap
// 提供 mountDOM
hooks.mountDOM.tap('provide mount dom', (dom: Element) => {
if (mountDOM) return console.error("Can't set mountDOM repeatedly");
mountDOM = dom;
// trigger afterMountDOM hook
setTimeout(() => {
hooks.afterMountDOM.call(mountDOM);
});
});
// 初始化提供过 mountDOM 时,使用初始化的 mountDOM
if (initedMountDOM) {
hooks.mountDOM.call(initedMountDOM);
}
// 触发 refresh、mountDOM 提供、项目注册、配置获取完成、history 更新时 更新项目
if (history) {
history.listen(() => refresh());
}
hooks.refresh.tap('refresh', () => refresh());
hooks.afterConfig.tap('refresh afterConfig', () => refresh());
hooks.afterMountDOM.tap('refresh afterMountDOM', () => refresh());
hooks.afterRegister.tap('refresh afterRegister', () => refresh());
const innerShared: InnerShared = {
loadResources: (projectConfig: ProjectConfig, onError: OnError) => {
return loadResources(projectConfig, onError);
}
};
// 注册插件
const registerPlugin = (plugin: Plugin) => {
plugin.call({ hooks, innerShared });
};
plugins.forEach(plugin => registerPlugin(plugin));
interface Instance {
register: typeof register;
hooks: Hooks;
refresh: typeof refresh;
[key: string]: any;
}
const amendInnerShared = (amendProps: any) => Object.assign(innerShared, amendProps);
hooks.amendInnerShared.call(innerShared, amendInnerShared);
// 返回的实例
let instance: Instance = {
register,
hooks,
refresh
};
instance.loadResources = innerShared.loadResources;
instance.loadProject = async (projectKey: string) => await innerShared.loadResources(_config[projectKey], onError);
// 挂载插件提供的实例属性
const amendInstance = (amendedProps: Instance) => Object.assign(instance, amendedProps);
hooks.amendInstance.call(instance, amendInstance);
const amendHooks = (amendedHooks: { name: Hook }) => Object.assign(hooks, amendedHooks);
hooks.amendHooks.call(hooks, amendHooks);
try {
(async () => {
if (!config) {
console.error(`Must provide a config`);
} else if (typeof config === 'function') {
_config = await config();
} else {
_config = config;
}
hooks.afterConfig.call(_config, instance);
})();
} catch (e) {
hooks.error.call(e);
console.error(e);
}
return instance;
};
export default rapiop;