-
Notifications
You must be signed in to change notification settings - Fork 126
/
Loader.tsx
399 lines (349 loc) · 11.8 KB
/
Loader.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
397
398
399
import React from 'react';
import PropTypes from 'prop-types';
import debounce from 'lodash.debounce';
import { ReactNodePropTypes } from '../../lib/utils';
import * as LayoutEvents from '../../lib/LayoutEvents';
import { Spinner, SpinnerProps } from '../Spinner';
import { Nullable } from '../../typings/utility-types';
import { ThemeContext } from '../../lib/theming/ThemeContext';
import { Theme } from '../../lib/theming/Theme';
import { ZIndex } from '../../internal/ZIndex';
import { CommonWrapper, CommonProps } from '../../internal/CommonWrapper';
import { cx } from '../../lib/theming/Emotion';
import { isTestEnv } from '../../lib/currentEnvironment';
import { TaskWithDelayAndMinimalDuration } from '../../lib/taskWithDelayAndMinimalDuration';
import { getTabbableElements } from '../../lib/dom/tabbableHelpers';
import { rootNode, TSetRootNode } from '../../lib/rootNode';
import { getDOMRect } from '../../lib/dom/getDOMRect';
import { styles } from './Loader.styles';
export interface LoaderProps extends CommonProps {
children?: React.ReactNode;
/**
* Флаг переключения состояния лоадера
* @default false
*/
active: boolean;
caption?: SpinnerProps['caption'];
/**
* Компонент заменяющий спиннер.
*/
component?: React.ReactNode;
className?: string;
type?: 'mini' | 'normal' | 'big';
/**
* Время в миллисекундах для показа вуали без спиннера.
* @default 300
*/
delayBeforeSpinnerShow: number;
/**
* Минимальное время в миллисекундах для показа спиннера
* @default 1000
*/
minimalDelayBeforeSpinnerHide: number;
}
export interface LoaderState {
isStickySpinner: boolean;
isSpinnerVisible: boolean;
isLoaderActive: boolean;
spinnerStyle?: object;
}
export const LoaderDataTids = {
veil: 'Loader__Veil',
spinner: 'Loader__Spinner',
} as const;
/**
* DRAFT - лоадер-контейнер
*/
@rootNode
export class Loader extends React.Component<LoaderProps, LoaderState> {
public static __KONTUR_REACT_UI__ = 'Loader';
public static defaultProps: Partial<LoaderProps> = {
type: Spinner.Types.normal,
active: false,
delayBeforeSpinnerShow: isTestEnv ? 0 : 300,
minimalDelayBeforeSpinnerHide: isTestEnv ? 0 : 1000,
};
public static propTypes = {
/**
* показываем лоадер или нет
*/
active: PropTypes.bool,
/**
* Текст рядом с лоадером.
*
* @default "Загрузка"
*/
caption: Spinner.propTypes.caption,
component: ReactNodePropTypes,
/**
* Класс для обертки
*/
className: PropTypes.string,
/**
* Тип спиннера: mini, normal, big
*
* @default normal
*
* Spinner.types - все доступные типы
*/
type: PropTypes.oneOf(Object.keys(Spinner.Types)),
/**
* Время в миллисекундах для показа вуали без спиннера.
* @default 300
*/
delayBeforeSpinnerShow: PropTypes.number,
/**
* Минимальное время в миллисекундах для показа спиннера
* @default 1000
*/
minimalDelayBeforeSpinnerHide: PropTypes.number,
};
private theme!: Theme;
private setRootNode!: TSetRootNode;
private spinnerContainerNode: Nullable<HTMLDivElement>;
private childrenContainerNode: Nullable<HTMLDivElement>;
private spinnerNode: Nullable<HTMLDivElement>;
private layoutEvents: Nullable<{ remove: () => void }>;
private spinnerTask: TaskWithDelayAndMinimalDuration;
private childrenObserver: Nullable<MutationObserver>;
constructor(props: LoaderProps) {
super(props);
this.spinnerContainerNode = null;
this.childrenContainerNode = null;
this.childrenObserver = null;
this.spinnerNode = null;
this.state = {
isStickySpinner: false,
isSpinnerVisible: false,
isLoaderActive: false,
};
this.spinnerTask = new TaskWithDelayAndMinimalDuration({
delayBeforeTaskStart: this.props.delayBeforeSpinnerShow,
durationOfTask: this.props.minimalDelayBeforeSpinnerHide,
taskStartCallback: () => this.setState({ isSpinnerVisible: true }),
taskStopCallback: () => this.setState({ isSpinnerVisible: false }),
});
}
public componentDidMount() {
this.checkSpinnerPosition();
this.props.active && this.spinnerTask.start();
this.layoutEvents = LayoutEvents.addListener(debounce(this.checkSpinnerPosition, 10));
if (this.props.active) {
this.disableChildrenFocus();
}
}
public componentDidUpdate(prevProps: Readonly<LoaderProps>, prevState: Readonly<LoaderState>) {
const { component, active, delayBeforeSpinnerShow, minimalDelayBeforeSpinnerHide } = this.props;
const { isLoaderActive } = this.state;
if ((active && !prevProps.active) || prevProps.component !== component) {
this.checkSpinnerPosition();
}
if (
delayBeforeSpinnerShow !== prevProps.delayBeforeSpinnerShow ||
minimalDelayBeforeSpinnerHide !== prevProps.minimalDelayBeforeSpinnerHide
) {
this.spinnerTask.update({
delayBeforeTaskStart: delayBeforeSpinnerShow,
durationOfTask: minimalDelayBeforeSpinnerHide,
});
}
if (active !== prevProps.active) {
active ? this.spinnerTask.start() : this.spinnerTask.stop();
}
if (isLoaderActive !== prevState.isLoaderActive) {
if (isLoaderActive) {
this.disableChildrenFocus();
} else {
this.enableChildrenFocus();
}
}
}
public componentWillUnmount() {
this.makeUnobservable();
if (this.layoutEvents) {
this.layoutEvents.remove();
}
this.spinnerTask.clearTask();
}
public static getDerivedStateFromProps(props: LoaderProps, state: LoaderState): Partial<LoaderState> {
if (props.active && !state.isLoaderActive) {
return {
isLoaderActive: true,
};
}
if (state.isLoaderActive && !(props.active || state.isSpinnerVisible)) {
return {
isLoaderActive: false,
};
}
return state;
}
public render() {
return (
<ThemeContext.Consumer>
{(theme) => {
this.theme = theme;
return this.renderMain();
}}
</ThemeContext.Consumer>
);
}
private renderMain() {
const { type, caption, component } = this.props;
const { isLoaderActive } = this.state;
return (
<CommonWrapper rootNodeRef={this.setRootNode} {...this.props}>
<div className={styles.loader()} data-tid={isLoaderActive ? LoaderDataTids.veil : ''}>
<ZIndex
priority={'Loader'}
applyZIndex={isLoaderActive}
coverChildren={isLoaderActive}
style={{ height: '100%' }}
wrapperRef={this.childrenRef}
>
{this.props.children}
</ZIndex>
{isLoaderActive && (
<ZIndex
wrapperRef={this.spinnerRef}
priority={'Loader'}
className={cx({
[styles.active(this.theme)]: isLoaderActive,
})}
>
{this.state.isSpinnerVisible && this.renderSpinner(type, caption, component)}
</ZIndex>
)}
</div>
</CommonWrapper>
);
}
private childrenRef = (element: HTMLDivElement | null) => {
this.childrenContainerNode = element;
};
private spinnerRef = (element: HTMLDivElement | null) => {
this.spinnerContainerNode = element;
};
private renderSpinner(type?: 'mini' | 'normal' | 'big', caption?: React.ReactNode, component?: React.ReactNode) {
return (
<span
data-tid={LoaderDataTids.spinner}
className={cx(styles.spinnerContainer(), { [styles.spinnerContainerSticky()]: this.state.isStickySpinner })}
style={this.state.spinnerStyle}
>
<div
className={styles.spinnerComponentWrapper()}
ref={(element) => {
this.spinnerNode = element;
}}
>
{component !== undefined ? component : <Spinner type={type} caption={caption} />}
</div>
</span>
);
}
private checkSpinnerPosition = () => {
if (!this.spinnerContainerNode) {
return;
}
const {
top: containerTop,
right: containerRight,
bottom: containerBottom,
left: containerLeft,
height: containerHeight,
width: containerWidth,
} = getDOMRect(this.spinnerContainerNode);
const windowHeight = window.innerHeight;
const windowWidth = window.innerWidth;
// Если контейнер не больше высоты и не шире окна,
// то просто выравниваем по центру
if (windowHeight >= containerHeight && windowWidth >= containerWidth) {
this.setState({
isStickySpinner: false,
spinnerStyle: {},
});
return;
}
const spinnerStyle: {
top?: number;
right: number;
bottom: number;
left: number;
} = {
top: 30,
right: 0,
bottom: 30,
left: 0,
};
// ПО ВЕРТИКАЛИ
// Если верхний край контейнера ниже верхнего края окна,
// то сдвигаем и лоадер
if (containerTop > 0) {
spinnerStyle.top = containerTop + 30;
}
// Если нижний край контейнера выше нижнего края окна,
// то сдвигаем и лоадер
if (containerBottom < windowHeight) {
spinnerStyle.bottom = Math.abs(windowHeight - containerBottom) + 30;
}
// Если знаем высоту спиннера и нижний край контейнера поднимается
// выше отступа на высоту спиннера, то убираем верхнюю позицию лоадера
const spinnerHeight = getDOMRect(this.spinnerNode).height;
if (spinnerHeight && spinnerStyle.bottom >= windowHeight - spinnerHeight) {
delete spinnerStyle.top;
}
// ПО ГОРИЗОНТАЛИ
// Если левый край контейнера правее левого края окна,
// то сдвигаем и лоадер
if (containerLeft > 0) {
spinnerStyle.left = containerLeft;
}
// Если правый край контейнера левее правого края окна,
// то сдвигаем и лоадер
if (containerRight < windowWidth) {
spinnerStyle.right = windowWidth - containerRight;
}
this.setState({
isStickySpinner: true,
spinnerStyle,
});
};
private disableChildrenFocus = () => {
if (!this.childrenObserver) {
this.makeObservable();
}
const tabbableElements = getTabbableElements(this.childrenContainerNode);
tabbableElements.forEach((el) => {
if (!el.hasAttribute('origin-tabindex')) {
el.setAttribute('origin-tabindex', el.tabIndex.toString());
}
el.tabIndex = -1;
});
};
private enableChildrenFocus = () => {
this.makeUnobservable();
// NOTE: NodeList doesn't support 'forEach' method in IE11 and other older browsers
Array.from(document.querySelectorAll('[origin-tabindex]')).forEach((el) => {
el.setAttribute('tabindex', el.getAttribute('origin-tabindex') ?? '0');
el.removeAttribute('origin-tabindex');
});
};
private makeObservable = () => {
const target = this.childrenContainerNode;
if (!target) {
return;
}
const config = {
childList: true,
subtree: true,
};
const observer = new MutationObserver(this.disableChildrenFocus);
observer.observe(target, config);
this.childrenObserver = observer;
};
private makeUnobservable = () => {
this.childrenObserver?.disconnect();
this.childrenObserver = null;
};
}