forked from grafana/grafana
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcreate-mfe.ts
319 lines (247 loc) · 9.73 KB
/
create-mfe.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
declare let __webpack_public_path__: string;
// This is a path to the public folder without '/build'
window.__grafana_public_path__ =
__webpack_public_path__.substring(0, __webpack_public_path__.lastIndexOf('build/')) || __webpack_public_path__;
import { isNull, merge, noop, pick } from 'lodash';
import React, { ComponentType } from 'react';
import ReactDOM from 'react-dom';
import { createTheme, GrafanaThemeType } from '@grafana/data';
import { createFnColors } from '@grafana/data/src/themes/fnCreateColors';
import { GrafanaTheme2 } from '@grafana/data/src/themes/types';
import { ThemeChangedEvent } from '@grafana/runtime';
import { GrafanaBootConfig } from '@grafana/runtime/src/config';
import { getTheme } from '@grafana/ui';
import appEvents from 'app/core/app_events';
import config from 'app/core/config';
import {
FnGlobalState,
updatePartialFnStates,
updateFnState,
INITIAL_FN_STATE,
FnPropMappedFromState,
fnStateProps,
} from 'app/core/reducers/fn-slice';
import { backendSrv } from 'app/core/services/backend_srv';
import fn_app from 'app/fn_app';
import { FnLoggerService } from 'app/fn_logger';
import { dispatch } from 'app/store/store';
import { FNDashboardProps, FailedToMountGrafanaErrorName } from './types';
/**
* NOTE:
* Qiankun expects Promise. Otherwise warnings are logged and life cycle hooks do not work
*/
/* eslint-disable-next-line */
export declare type LifeCycleFn = (app: any, global: typeof window) => Promise<any>;
/**
* NOTE: single-spa and qiankun lifeCycles
*/
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
export declare type FrameworkLifeCycles = {
beforeLoad: LifeCycleFn | LifeCycleFn[];
beforeMount: LifeCycleFn | LifeCycleFn[];
afterMount: LifeCycleFn | LifeCycleFn[];
beforeUnmount: LifeCycleFn | LifeCycleFn[];
afterUnmount: LifeCycleFn | LifeCycleFn[];
bootstrap: LifeCycleFn | LifeCycleFn[];
mount: LifeCycleFn | LifeCycleFn[];
unmount: LifeCycleFn | LifeCycleFn[];
update: LifeCycleFn | LifeCycleFn[];
};
type DeepPartial<T> = {
[P in keyof T]?: DeepPartial<T[P]>;
};
class createMfe {
private static readonly containerSelector = '#grafanaRoot';
private static readonly logPrefix = '[FN Grafana]';
mode: FNDashboardProps['mode'];
static Component: ComponentType<Omit<FNDashboardProps, FnPropMappedFromState>>;
constructor(readonly props: FNDashboardProps) {
this.mode = props.mode;
}
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
private static logger = (...args: any[]) => console.log(createMfe.logPrefix, ...args);
static getLifeCycles(component: ComponentType<Omit<FNDashboardProps, FnPropMappedFromState>>) {
const lifeCycles: FrameworkLifeCycles = {
bootstrap: this.boot(),
mount: this.mountFnApp(component),
unmount: this.unMountFnApp(),
update: this.updateFnApp(),
afterMount: () => Promise.resolve(),
beforeMount: () => Promise.resolve(),
afterUnmount: () => Promise.resolve(),
beforeUnmount: () => Promise.resolve(),
beforeLoad: () => Promise.resolve(),
};
return lifeCycles;
}
static create(component: ComponentType<Omit<FNDashboardProps, FnPropMappedFromState>>) {
return createMfe.getLifeCycles(component);
}
static boot() {
return () => fn_app.init();
}
private static toggleTheme = (mode: FNDashboardProps['mode']): GrafanaThemeType.Light | GrafanaThemeType.Dark =>
mode === 'dark' ? GrafanaThemeType.Light : GrafanaThemeType.Dark;
private static get styleSheetLink() {
const stylesheetLink = document.createElement('link');
stylesheetLink.rel = 'stylesheet';
return stylesheetLink;
}
private static createGrafanaTheme2(mode: FNDashboardProps['mode']) {
config.theme2 = createTheme({
colors: {
mode,
},
});
config.theme2.colors = createFnColors({ mode });
config.theme2.v1 = getTheme(mode);
config.theme2.v1.colors = config.theme.colors;
return config.theme2;
}
private static getPartialBootConfigWithTheme(theme2: GrafanaTheme2) {
const partial: DeepPartial<GrafanaBootConfig> = {
theme: theme2.v1,
bootData: { user: { lightTheme: theme2.isLight } },
};
return partial;
}
private static mergeBootConfigs(bootConfig: GrafanaBootConfig, partialBootConfig: DeepPartial<GrafanaBootConfig>) {
return merge({}, bootConfig, partialBootConfig);
}
private static publishTheme(theme: GrafanaTheme2) {
appEvents.publish(new ThemeChangedEvent(theme));
}
// NOTE: based on grafana function: 'toggleTheme'
private static removeThemeLinks(modeToBeTurnedOff: GrafanaThemeType.Light | GrafanaThemeType.Dark, timeout?: number) {
Array.from(document.getElementsByTagName('link')).forEach(createMfe.removeThemeLink(modeToBeTurnedOff, timeout));
}
private static removeThemeLink(modeToBeTurnedOff: FNDashboardProps['mode'], timeout?: number) {
return (link: HTMLLinkElement) => {
if (!link.href?.includes(`build/grafana.${modeToBeTurnedOff}`)) {
return;
}
if (isNull(timeout)) {
link.remove();
return;
}
// Remove existing link after a 500ms to allow new css to load to avoid flickering
// If we add new css at the same time we remove current one the page will be rendered without css
// As the new css file is loading
setTimeout(link.remove, timeout);
};
}
/**
* NOTE:
* If isRuntimeOnly then the stylesheets of the turned off theme are not removed
*/
private static loadFnTheme = (mode: FNDashboardProps['mode'] = GrafanaThemeType.Light, isRuntimeOnly = false) => {
createMfe.logger('Trying to load theme.', { mode });
const grafanaTheme2 = createMfe.createGrafanaTheme2(mode);
const partialBootConfigWithTheme = createMfe.getPartialBootConfigWithTheme(grafanaTheme2);
const bootConfigWithTheme = createMfe.mergeBootConfigs(config, partialBootConfigWithTheme);
createMfe.publishTheme(bootConfigWithTheme.theme2);
if (isRuntimeOnly) {
createMfe.logger('Successfully loaded theme', { mode });
return;
}
createMfe.removeThemeLinks(createMfe.toggleTheme(mode));
const newCssLink = createMfe.styleSheetLink;
newCssLink.href = config.bootData.themePaths[mode];
document.body.appendChild(newCssLink);
createMfe.logger('Successfully loaded theme.', { mode });
};
private static getContainer(props: FNDashboardProps) {
const parentElement = props.container || document;
return parentElement.querySelector(createMfe.containerSelector);
}
static mountFnApp(Component: ComponentType<Omit<FNDashboardProps, FnPropMappedFromState>>) {
const lifeCycleFn: FrameworkLifeCycles['mount'] = (props: FNDashboardProps) => {
createMfe.logger('Trying to mount grafana...');
return new Promise((res, rej) => {
try {
createMfe.loadFnTheme(props.mode);
createMfe.Component = Component;
const initialState: FnGlobalState = {
...INITIAL_FN_STATE,
FNDashboard: true,
...pick(props, ...fnStateProps),
};
FnLoggerService.log(null, '[FN Grafana] Dispatching initial state.', { initialState });
dispatch(updateFnState(initialState));
createMfe.renderMfeComponent(props, () => {
createMfe.logger('Mounted grafana.', { props });
return res(true);
});
} catch (err) {
const message = `[FN Grafana]: Failed to mount grafana. ${err}`;
FnLoggerService.log(null, message);
const fnError = new Error(message);
const name: FailedToMountGrafanaErrorName = 'FailedToMountGrafana';
fnError.name = name;
return rej(fnError);
}
});
};
return lifeCycleFn;
}
static unMountFnApp() {
const lifeCycleFn: FrameworkLifeCycles['unmount'] = (props: FNDashboardProps) => {
const container = createMfe.getContainer(props);
if (container) {
createMfe.logger('Trying to unmount grafana...');
ReactDOM.unmountComponentAtNode(container);
createMfe.logger('Successfully unmounted grafana.');
} else {
createMfe.logger('Failed to unmount grafana. Container does not exist.');
}
backendSrv.cancelAllInFlightRequests();
return Promise.resolve(!!container);
};
return lifeCycleFn;
}
static updateFnApp() {
const lifeCycleFn: FrameworkLifeCycles['update'] = ({ mode, ...other }: FNDashboardProps) => {
if (mode) {
createMfe.logger('Trying to update grafana with theme.', { mode });
dispatch(
updatePartialFnStates({
mode,
})
);
/**
* NOTE:
* Here happens the theme change.
*
* TODO:
* We could probably made the theme change smoother
* if we use state to update the theme
*/
createMfe.loadFnTheme(mode);
}
if (other.uid) {
createMfe.logger('Trying to update grafana with hidden variables.', { updatedProps: other });
dispatch(
updatePartialFnStates({
uid: other.uid,
hiddenVariables: other.hiddenVariables,
slug: other.slug,
version: other.version,
queryParams: other.queryParams,
controlsContainer: other.controlsContainer,
})
);
}
// NOTE: The false/true value does not change anything
return Promise.resolve(true);
};
return lifeCycleFn;
}
static renderMfeComponent(props: FNDashboardProps, onSuccess = noop) {
const container = createMfe.getContainer(props);
ReactDOM.render(React.createElement(createMfe.Component, props), container, () => {
createMfe.logger('Created mfe component.', { props, container });
onSuccess();
});
}
}
export { createMfe };