-
Notifications
You must be signed in to change notification settings - Fork 124
/
Copy pathInsightRenderer.tsx
396 lines (351 loc) · 14.1 KB
/
InsightRenderer.tsx
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
// (C) 2020-2025 GoodData Corporation
import React, { useCallback, useEffect, useRef } from "react";
import { v4 as uuidv4 } from "uuid";
// eslint-disable-next-line react/no-deprecated
import { render } from "react-dom";
import noop from "lodash/noop.js";
import isEqual from "lodash/isEqual.js";
import compose from "lodash/flowRight.js";
import { injectIntl, WrappedComponentProps } from "react-intl";
import { IExecutionFactory, IExportResult, IUserWorkspaceSettings } from "@gooddata/sdk-backend-spi";
import {
IInsightDefinition,
insightProperties,
IColorPalette,
insightTitle,
ITheme,
insightSetProperties,
insightVisualizationUrl,
insightVisualizationType,
} from "@gooddata/sdk-model";
import {
IVisualization,
IVisProps,
FullVisualizationCatalog,
IInsightViewProps,
unmountComponentsAtNodes,
} from "../internal/index.js";
import {
OnError,
fillMissingTitles,
fillMissingFormats,
ignoreTitlesForSimpleMeasures,
ILocale,
withContexts,
DefaultLocale,
LoadingComponent,
ErrorComponent,
IExportFunction,
IExtendedExportConfig,
IntlWrapper,
} from "@gooddata/sdk-ui";
import {
ExecutionFactoryUpgradingToExecByReference,
ExecutionFactoryWithFixedFilters,
} from "@gooddata/sdk-backend-base";
import { withTheme } from "@gooddata/sdk-ui-theme-provider";
import { Root, _createRoot } from "../internal/createRootProvider.js";
/**
* @internal
*/
export interface IInsightRendererProps
extends Omit<IInsightViewProps, "insight" | "TitleComponent" | "onInsightLoaded" | "showTitle"> {
insight: IInsightDefinition | undefined;
locale: ILocale;
settings: IUserWorkspaceSettings | undefined;
colorPalette: IColorPalette | undefined;
onError?: OnError;
theme?: ITheme;
afterRender?: () => void;
}
const getElementId = () => `gd-vis-${uuidv4()}`;
const visualizationUriRootStyle: React.CSSProperties = {
height: "100%",
display: "flex",
flex: "1 1 auto",
flexDirection: "column",
};
// this needs to be a pure component as it can happen that this might be rendered multiple times
// with the same props (referentially) - this might make the rendered visualization behave unpredictably
// and is bad for performance so we need to make sure the re-renders are performed only if necessary
class InsightRendererCore extends React.PureComponent<IInsightRendererProps & WrappedComponentProps> {
private elementId = getElementId();
private visualization: IVisualization | undefined;
private containerRef = React.createRef<HTMLDivElement>();
/**
* The component may render both visualization and config panel. In React18 we therefore need two
* roots with their respective render methods. This Map holds the roots for both and provides
* render and unmount methods whenever needed.
*/
private reactRootsMap: Map<HTMLElement, Root> = new Map();
public static defaultProps: Pick<
IInsightRendererProps,
| "ErrorComponent"
| "filters"
| "drillableItems"
| "LoadingComponent"
| "pushData"
| "locale"
| "afterRender"
> = {
ErrorComponent,
filters: [],
drillableItems: [],
LoadingComponent,
pushData: noop,
locale: DefaultLocale,
afterRender: () => {},
};
private unmountVisualization = () => {
if (this.visualization) {
this.visualization.unmount();
}
this.visualization = undefined;
};
private updateVisualization = () => {
// if the container no longer exists, update was called after unmount -> do nothing
if (!this.visualization || !this.containerRef.current) {
return;
}
// if there is no insight, bail early
if (!this.props.insight) {
return;
}
const { config = {} } = this.props;
const { responsiveUiDateFormat } = this.props.settings ?? {};
const visProps: IVisProps = {
locale: this.props.locale,
dateFormat: responsiveUiDateFormat,
custom: {
drillableItems: this.props.drillableItems,
lastSavedVisClassUrl: insightVisualizationUrl(this.props.insight),
},
config: {
separators: config.separators,
colorPalette: this.props.colorPalette,
mapboxToken: config.mapboxToken,
forceDisableDrillOnAxes: config.forceDisableDrillOnAxes,
isInEditMode: config.isInEditMode,
isExportMode: config.isExportMode,
enableExecutionCancelling: config.enableExecutionCancelling,
},
executionConfig: this.props.execConfig,
customVisualizationConfig: config,
theme: this.props.theme,
};
const visClass = insightVisualizationType(this.props.insight);
let insight = fillMissingFormats(fillMissingTitles(this.props.insight, this.props.locale));
/**
* Ignore titles for simple measures in all visualizations except for repeater.
* This is not nice, and InsightRenderer should not be aware of the visualization types.
* However, repeater is transforming simple measures to inline ones, so we need to keep the titles for them.
* We can remove this once we have a better solution on execution level,
* or all the visualizations start to use actual measure titles specified in AD, and not measure metadata titles.
* See also https://gooddata.atlassian.net/browse/SD-1012
*/
if (visClass !== "repeater") {
insight = ignoreTitlesForSimpleMeasures(insight);
}
this.visualization.update(visProps, insight, {}, this.getExecutionFactory());
};
private setupVisualization = async () => {
// if there is no insight, bail early
if (!this.props.insight) {
return;
}
// the visualization we may have from earlier is no longer valid -> get rid of it
this.unmountVisualization();
const visualizationFactory = FullVisualizationCatalog.forInsight(this.props.insight).getFactory();
this.visualization = visualizationFactory({
backend: this.props.backend,
callbacks: {
onError: (error) => {
this.props.onError?.(error);
this.props.onLoadingChanged?.({ isLoading: false });
},
onLoadingChanged: this.props.onLoadingChanged,
pushData: this.props.pushData,
onDrill: this.props.onDrill,
onDataView: this.props.onDataView,
onExportReady: this.onExportReadyDecorator,
afterRender: this.props.afterRender,
},
configPanelElement: () => {
const rootNode =
(this.containerRef.current?.getRootNode() as Document | ShadowRoot) ?? document;
// this is apparently a well-know constant (see BaseVisualization)
return rootNode.querySelector(".gd-configuration-panel-content");
},
element: () => {
const rootNode =
(this.containerRef.current?.getRootNode() as Document | ShadowRoot) ?? document;
return rootNode.querySelector(`#${this.elementId}`);
},
environment: "dashboards", // TODO get rid of this
locale: this.props.locale,
projectId: this.props.workspace,
visualizationProperties: insightProperties(this.props.insight),
featureFlags: this.props.settings,
renderFun: this.getReactRenderFunction(),
unmountFun: this.getReactUnmountFunction(),
});
};
private getReactRenderFunction = () => {
if (_createRoot) {
return (children: any, element: HTMLElement) => {
if (!this.reactRootsMap.get(element)) {
this.reactRootsMap.set(element, _createRoot(element));
}
this.reactRootsMap.get(element).render(children);
};
} else {
// eslint-disable-next-line react/no-deprecated
return render;
}
};
private getReactUnmountFunction = () => {
if (_createRoot) {
return () => this.reactRootsMap.forEach((root) => root.render(null));
} else {
return (elementsOrSelectors: (string | HTMLElement)[]) =>
unmountComponentsAtNodes(elementsOrSelectors);
}
};
private onExportReadyDecorator = (exportFunction: IExportFunction): void => {
if (!this.props.onExportReady) {
return;
}
const decorator = (exportConfig: IExtendedExportConfig): Promise<IExportResult> => {
if (exportConfig.title || !this.props.insight) {
return exportFunction(exportConfig);
}
return exportFunction({
...exportConfig,
title: insightTitle(this.props.insight),
});
};
this.props.onExportReady(decorator);
};
private getExecutionFactory = (): IExecutionFactory => {
const factory = this.props.backend.workspace(this.props.workspace).execution();
if (this.props.executeByReference) {
/*
* When executing by reference, decorate the original execution factory so that it
* transparently routes `forInsight` to `forInsightByRef` AND adds the filters
* from InsightView props.
*
* Code will pass this factory over to the pluggable visualizations - they will do execution
* `forInsight` and under the covers things will be routed and done differently without the
* plug viz knowing.
*/
return new ExecutionFactoryUpgradingToExecByReference(
new ExecutionFactoryWithFixedFilters(factory, this.props.filters),
);
}
return factory;
};
private componentDidMountInner = async () => {
await this.setupVisualization();
return this.updateVisualization();
};
public componentDidMount(): void {
this.componentDidMountInner();
}
private componentDidUpdateInner = async (prevProps: IInsightRendererProps) => {
/**
* Ignore properties when comparing insights to determine if a new setup is needed: changes to properties
* only will be handled using the updateVisualization without unnecessary new setup just fine.
*/
const prevInsightForCompare = prevProps.insight && insightSetProperties(prevProps.insight, {});
const newInsightForCompare = this.props.insight && insightSetProperties(this.props.insight, {});
const needsNewSetup =
!isEqual(newInsightForCompare, prevInsightForCompare) ||
!isEqual(this.props.filters, prevProps.filters) ||
!isEqual(this.props.settings, prevProps.settings) ||
this.props.workspace !== prevProps.workspace;
if (needsNewSetup) {
await this.setupVisualization();
}
return this.updateVisualization();
};
public componentDidUpdate(prevProps: IInsightRendererProps & WrappedComponentProps): void {
this.componentDidUpdateInner(prevProps);
}
public componentWillUnmount() {
this.unmountVisualization();
if (_createRoot) {
// In order to avoid race conditions when mounting and unmounting synchronously,
// we use timeout for React18.
// https://github.com/facebook/react/issues/25675
this.reactRootsMap.forEach((root) => setTimeout(() => root.unmount(), 0));
}
}
public render() {
return (
// never ever dynamically change the props of this div, otherwise bad things will happen
// e.g. visualization being rendered multiple times, etc.
<div
className="visualization-uri-root"
id={this.elementId}
ref={this.containerRef}
style={visualizationUriRootStyle}
/>
);
}
}
export const IntlInsightRenderer = compose(injectIntl, withTheme, withContexts)(InsightRendererCore);
/**
* Updated callback (callback with a different reference) is not properly propagated to the "visualization" instance
* (because it only takes the callbacks provided on the first render)
* Workaround it by storing the updated callback to the ref and calling it instead.
*/
function useUpdatableCallback<T extends (...args: any[]) => any>(callback: T): T {
const pushDataCached = useRef(callback);
useEffect(() => {
pushDataCached.current = callback;
}, [callback]);
// eslint-disable-next-line react-hooks/exhaustive-deps
return useCallback<T>(
((...args) => {
if (pushDataCached.current) {
pushDataCached.current(...args);
}
}) as T,
[],
);
}
/**
* Renders insight passed as a parameter.
*
* @internal
*/
export const InsightRenderer: React.FC<IInsightRendererProps> = (props) => {
const {
pushData,
onDrill: onDrillCallBack,
onError: onErrorCallBack,
onExportReady: onExportReadyCallback,
onLoadingChanged: onLoadingChangedCallback,
onDataView: onDataViewCallback,
...resProps
} = props;
const onPushData = useUpdatableCallback(pushData);
const onDrill = useUpdatableCallback(onDrillCallBack);
const onError = useUpdatableCallback(onErrorCallBack);
const onExportReady = useUpdatableCallback(onExportReadyCallback);
const onLoadingChanged = useUpdatableCallback(onLoadingChangedCallback);
const onDataView = useUpdatableCallback(onDataViewCallback);
return (
<IntlWrapper locale={props.locale}>
<IntlInsightRenderer
pushData={onPushData}
onDrill={onDrill}
onError={onError}
onExportReady={onExportReady}
onLoadingChanged={onLoadingChanged}
onDataView={onDataView}
{...resProps}
/>
</IntlWrapper>
);
};