-
Notifications
You must be signed in to change notification settings - Fork 919
/
react_expression_renderer.tsx
214 lines (194 loc) · 7.42 KB
/
react_expression_renderer.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
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Any modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { useRef, useEffect, useState, useLayoutEffect } from 'react';
import classNames from 'classnames';
import { Observable, Subscription } from 'rxjs';
import { filter } from 'rxjs/operators';
import useShallowCompareEffect from 'react-use/lib/useShallowCompareEffect';
import { EuiLoadingChart, EuiProgress } from '@elastic/eui';
import { euiThemeVars } from '@osd/ui-shared-deps/theme';
import { IExpressionLoaderParams, ExpressionRenderError } from './types';
import { ExpressionAstExpression, IInterpreterRenderHandlers } from '../common';
import { ExpressionLoader } from './loader';
import { ExpressionRendererEvent } from './render';
// Accept all options of the runner as props except for the
// dom element which is provided by the component itself
export interface ReactExpressionRendererProps extends IExpressionLoaderParams {
className?: string;
dataAttrs?: string[];
expression: string | ExpressionAstExpression;
renderError?: (
message?: string | null,
error?: ExpressionRenderError | null
) => React.ReactElement | React.ReactElement[];
padding?: 'xs' | 's' | 'm' | 'l' | 'xl';
onEvent?: (event: ExpressionRendererEvent) => void;
/**
* An observable which can be used to re-run the expression without destroying the component
*/
reload$?: Observable<unknown>;
}
export type ReactExpressionRendererType = React.ComponentType<ReactExpressionRendererProps>;
interface State {
isEmpty: boolean;
isLoading: boolean;
error: null | ExpressionRenderError;
}
export type ExpressionRendererComponent = React.FC<ReactExpressionRendererProps>;
const defaultState: State = {
isEmpty: true,
isLoading: false,
error: null,
};
export const ReactExpressionRenderer = ({
className,
dataAttrs,
padding,
renderError,
expression,
onEvent,
reload$,
...expressionLoaderOptions
}: ReactExpressionRendererProps) => {
const mountpoint: React.MutableRefObject<null | HTMLDivElement> = useRef(null);
const [state, setState] = useState<State>({ ...defaultState });
const hasCustomRenderErrorHandler = !!renderError;
const expressionLoaderRef: React.MutableRefObject<null | ExpressionLoader> = useRef(null);
// flag to skip next render$ notification,
// because of just handled error
const hasHandledErrorRef = useRef(false);
// will call done() in LayoutEffect when done with rendering custom error state
const errorRenderHandlerRef: React.MutableRefObject<null | IInterpreterRenderHandlers> = useRef(
null
);
/* eslint-disable react-hooks/exhaustive-deps */
// OK to ignore react-hooks/exhaustive-deps because options update is handled by calling .update()
useEffect(() => {
const subs: Subscription[] = [];
expressionLoaderRef.current = new ExpressionLoader(mountpoint.current!, expression, {
...expressionLoaderOptions,
// react component wrapper provides different
// error handling api which is easier to work with from react
// if custom renderError is not provided then we fallback to default error handling from ExpressionLoader
onRenderError: hasCustomRenderErrorHandler
? (domNode, error, handlers) => {
errorRenderHandlerRef.current = handlers;
setState(() => ({
...defaultState,
isEmpty: false,
error,
}));
if (expressionLoaderOptions.onRenderError) {
expressionLoaderOptions.onRenderError(domNode, error, handlers);
}
}
: expressionLoaderOptions.onRenderError,
});
if (onEvent) {
subs.push(
expressionLoaderRef.current.events$.subscribe((event) => {
onEvent(event);
})
);
}
subs.push(
expressionLoaderRef.current.loading$.subscribe(() => {
hasHandledErrorRef.current = false;
setState((prevState) => ({ ...prevState, isLoading: true }));
}),
expressionLoaderRef.current.render$
.pipe(filter(() => !hasHandledErrorRef.current))
.subscribe((item) => {
setState(() => ({
...defaultState,
isEmpty: false,
}));
})
);
return () => {
subs.forEach((s) => s.unsubscribe());
if (expressionLoaderRef.current) {
expressionLoaderRef.current.destroy();
expressionLoaderRef.current = null;
}
errorRenderHandlerRef.current = null;
};
}, [hasCustomRenderErrorHandler, onEvent]);
useEffect(() => {
const subscription = reload$?.subscribe(() => {
if (expressionLoaderRef.current) {
expressionLoaderRef.current.update(expression, expressionLoaderOptions);
}
});
return () => subscription?.unsubscribe();
}, [reload$, expression, ...Object.values(expressionLoaderOptions)]);
// Re-fetch data automatically when the inputs change
useShallowCompareEffect(
() => {
if (expressionLoaderRef.current) {
expressionLoaderRef.current.update(expression, expressionLoaderOptions);
}
},
// when expression is changed by reference and when any other loaderOption is changed by reference
[{ expression, ...expressionLoaderOptions }]
);
/* eslint-enable react-hooks/exhaustive-deps */
// call expression loader's done() handler when finished rendering custom error state
useLayoutEffect(() => {
if (state.error && errorRenderHandlerRef.current) {
hasHandledErrorRef.current = true;
errorRenderHandlerRef.current.done();
errorRenderHandlerRef.current = null;
}
}, [state.error]);
const classes = classNames('expExpressionRenderer', className, {
'expExpressionRenderer-isEmpty': state.isEmpty,
'expExpressionRenderer-hasError': !!state.error,
});
const expressionStyles: React.CSSProperties = {};
// TODO: refactor to SCSS instead of getting values from theme: https://github.com/opensearch-project/OpenSearch-Dashboards/issues/5661
if (padding) {
expressionStyles.padding = euiThemeVars.paddingSizes[padding];
}
return (
<div {...dataAttrs} className={classes}>
{state.isEmpty && <EuiLoadingChart mono size="l" />}
{state.isLoading && <EuiProgress size="xs" color="accent" position="absolute" />}
{!state.isLoading &&
state.error &&
renderError &&
renderError(state.error.message, state.error)}
<div
className="expExpressionRenderer__expression"
style={expressionStyles}
ref={mountpoint}
/>
</div>
);
};