UNPKG

2.07 kBJavaScriptView Raw
1'use client';
2
3import * as React from 'react';
4import useLazyRef from '@mui/utils/useLazyRef';
5/**
6 * Lazy initialization container for the Ripple instance. This improves
7 * performance by delaying mounting the ripple until it's needed.
8 */
9export class LazyRipple {
10 /** React ref to the ripple instance */
11
12 /** If the ripple component should be mounted */
13
14 /** Promise that resolves when the ripple component is mounted */
15
16 /** If the ripple component has been mounted */
17
18 /** React state hook setter */
19
20 static create() {
21 return new LazyRipple();
22 }
23 static use() {
24 /* eslint-disable */
25 const ripple = useLazyRef(LazyRipple.create).current;
26 const [shouldMount, setShouldMount] = React.useState(false);
27 ripple.shouldMount = shouldMount;
28 ripple.setShouldMount = setShouldMount;
29 React.useEffect(ripple.mountEffect, [shouldMount]);
30 /* eslint-enable */
31
32 return ripple;
33 }
34 constructor() {
35 this.ref = {
36 current: null
37 };
38 this.mounted = null;
39 this.didMount = false;
40 this.shouldMount = false;
41 this.setShouldMount = null;
42 }
43 mount() {
44 if (!this.mounted) {
45 this.mounted = createControlledPromise();
46 this.shouldMount = true;
47 this.setShouldMount(this.shouldMount);
48 }
49 return this.mounted;
50 }
51 mountEffect = () => {
52 if (this.shouldMount && !this.didMount) {
53 if (this.ref.current !== null) {
54 this.didMount = true;
55 this.mounted.resolve();
56 }
57 }
58 };
59
60 /* Ripple API */
61
62 start(...args) {
63 this.mount().then(() => this.ref.current?.start(...args));
64 }
65 stop(...args) {
66 this.mount().then(() => this.ref.current?.stop(...args));
67 }
68 pulsate(...args) {
69 this.mount().then(() => this.ref.current?.pulsate(...args));
70 }
71}
72export default function useLazyRipple() {
73 return LazyRipple.use();
74}
75function createControlledPromise() {
76 let resolve;
77 let reject;
78 const p = new Promise((resolveFn, rejectFn) => {
79 resolve = resolveFn;
80 reject = rejectFn;
81 });
82 p.resolve = resolve;
83 p.reject = reject;
84 return p;
85}
\No newline at end of file