-
-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
helpers.ts
210 lines (182 loc) · 5.84 KB
/
helpers.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
// @ts-ignore
import global from 'global';
import { enableProdMode, NgModule, Component, NgModuleRef, Type, NgZone } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { BrowserModule } from '@angular/platform-browser';
import { Observable, ReplaySubject, Subscriber } from 'rxjs';
import { PartialStoryFn } from '@storybook/csf';
import { AppComponent } from './components/app.component';
import { STORY } from './app.token';
import { NgModuleMetadata, StoryFnAngularReturnType } from '../types';
import { AngularFramework } from '../types-6-0';
const { document } = global;
declare global {
interface Window {
NODE_ENV: 'string' | 'development' | undefined;
}
}
let platform: any = null;
let promises: Promise<NgModuleRef<any>>[] = [];
let storyData = new ReplaySubject<StoryFnAngularReturnType>(1);
const moduleClass = class DynamicModule {};
const componentClass = class DynamicComponent {};
type DynamicComponentType = typeof componentClass;
function storyDataFactory<T>(data: Observable<T>) {
return (ngZone: NgZone) =>
new Observable((subscriber: Subscriber<T>) => {
const sub = data.subscribe(
(v: T) => {
ngZone.run(() => subscriber.next(v));
},
(err) => {
ngZone.run(() => subscriber.error(err));
},
() => {
ngZone.run(() => subscriber.complete());
}
);
return () => {
sub.unsubscribe();
};
});
}
const getModule = (
declarations: (Type<any> | any[])[],
entryComponents: (Type<any> | any[])[],
bootstrap: (Type<any> | any[])[],
data: StoryFnAngularReturnType,
moduleMetadata: NgModuleMetadata
) => {
// Complete last ReplaySubject and create a new one for the current module
storyData.complete();
storyData = new ReplaySubject<StoryFnAngularReturnType>(1);
storyData.next(data);
const moduleMeta = {
declarations: [...declarations, ...(moduleMetadata.declarations || [])],
imports: [BrowserModule, FormsModule, ...(moduleMetadata.imports || [])],
providers: [
{ provide: STORY, useFactory: storyDataFactory(storyData.asObservable()), deps: [NgZone] },
...(moduleMetadata.providers || []),
],
entryComponents: [...entryComponents, ...(moduleMetadata.entryComponents || [])],
schemas: [...(moduleMetadata.schemas || [])],
bootstrap: [...bootstrap],
};
return NgModule(moduleMeta)(moduleClass);
};
const createComponentFromTemplate = (template: string, styles: string[]) => {
return Component({
template,
styles,
})(componentClass);
};
const extractNgModuleMetadata = (importItem: any): NgModule => {
const target = importItem && importItem.ngModule ? importItem.ngModule : importItem;
const decoratorKey = '__annotations__';
const decorators: any[] =
Reflect &&
Reflect.getOwnPropertyDescriptor &&
Reflect.getOwnPropertyDescriptor(target, decoratorKey)
? Reflect.getOwnPropertyDescriptor(target, decoratorKey).value
: target[decoratorKey];
if (!decorators || decorators.length === 0) {
return null;
}
const ngModuleDecorator: NgModule | undefined = decorators.find(
(decorator) => decorator instanceof NgModule
);
if (!ngModuleDecorator) {
return null;
}
return ngModuleDecorator;
};
const getExistenceOfComponentInModules = (
component: any,
declarations: any[],
imports: any[]
): boolean => {
if (declarations && declarations.some((declaration) => declaration === component)) {
// Found component in declarations array
return true;
}
if (!imports) {
return false;
}
return imports.some((importItem) => {
const extractedNgModuleMetadata = extractNgModuleMetadata(importItem);
if (!extractedNgModuleMetadata) {
// Not an NgModule
return false;
}
return getExistenceOfComponentInModules(
component,
extractedNgModuleMetadata.declarations,
extractedNgModuleMetadata.imports
);
});
};
const initModule = (storyFn: PartialStoryFn<AngularFramework>) => {
const storyObj = storyFn();
const { component, template, props, styles, moduleMetadata = {} } = storyObj;
const isCreatingComponentFromTemplate = Boolean(template);
const AnnotatedComponent = isCreatingComponentFromTemplate
? createComponentFromTemplate(template, styles)
: component;
const componentRequiresDeclaration =
isCreatingComponentFromTemplate ||
!getExistenceOfComponentInModules(
component,
moduleMetadata.declarations,
moduleMetadata.imports
);
const componentDeclarations = componentRequiresDeclaration
? [AppComponent, AnnotatedComponent]
: [AppComponent];
const story = {
component: AnnotatedComponent,
props,
};
return getModule(
componentDeclarations,
[AnnotatedComponent],
[AppComponent],
story,
moduleMetadata
);
};
const staticRoot = document.getElementById('root');
const insertDynamicRoot = () => {
const app = document.createElement('storybook-dynamic-app-root');
staticRoot.innerHTML = '';
staticRoot.appendChild(app);
};
const draw = (newModule: DynamicComponentType): void => {
if (!platform) {
insertDynamicRoot();
// eslint-disable-next-line no-undef
if (typeof NODE_ENV === 'string' && NODE_ENV !== 'development') {
try {
enableProdMode();
} catch (e) {
//
}
}
platform = platformBrowserDynamic();
promises.push(platform.bootstrapModule(newModule));
} else {
Promise.all(promises).then((modules) => {
modules.forEach((mod) => mod.destroy());
insertDynamicRoot();
promises = [];
promises.push(platform.bootstrapModule(newModule));
});
}
};
export const renderNgApp = (storyFn: PartialStoryFn<AngularFramework>, forced: boolean) => {
if (!forced) {
draw(initModule(storyFn));
} else {
storyData.next(storyFn());
}
};