useLazyRipple.js
2.42 KB
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
"use strict";
'use client';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.LazyRipple = void 0;
exports.default = useLazyRipple;
var React = _interopRequireWildcard(require("react"));
var _useLazyRef = _interopRequireDefault(require("@mui/utils/useLazyRef"));
/**
* Lazy initialization container for the Ripple instance. This improves
* performance by delaying mounting the ripple until it's needed.
*/
class LazyRipple {
/** React ref to the ripple instance */
/** If the ripple component should be mounted */
/** Promise that resolves when the ripple component is mounted */
/** If the ripple component has been mounted */
/** React state hook setter */
static create() {
return new LazyRipple();
}
static use() {
/* eslint-disable */
const ripple = (0, _useLazyRef.default)(LazyRipple.create).current;
const [shouldMount, setShouldMount] = React.useState(false);
ripple.shouldMount = shouldMount;
ripple.setShouldMount = setShouldMount;
React.useEffect(ripple.mountEffect, [shouldMount]);
/* eslint-enable */
return ripple;
}
constructor() {
this.ref = {
current: null
};
this.mounted = null;
this.didMount = false;
this.shouldMount = false;
this.setShouldMount = null;
}
mount() {
if (!this.mounted) {
this.mounted = createControlledPromise();
this.shouldMount = true;
this.setShouldMount(this.shouldMount);
}
return this.mounted;
}
mountEffect = () => {
if (this.shouldMount && !this.didMount) {
if (this.ref.current !== null) {
this.didMount = true;
this.mounted.resolve();
}
}
};
/* Ripple API */
start(...args) {
this.mount().then(() => this.ref.current?.start(...args));
}
stop(...args) {
this.mount().then(() => this.ref.current?.stop(...args));
}
pulsate(...args) {
this.mount().then(() => this.ref.current?.pulsate(...args));
}
}
exports.LazyRipple = LazyRipple;
function useLazyRipple() {
return LazyRipple.use();
}
function createControlledPromise() {
let resolve;
let reject;
const p = new Promise((resolveFn, rejectFn) => {
resolve = resolveFn;
reject = rejectFn;
});
p.resolve = resolve;
p.reject = reject;
return p;
}