1 | 'use client';
|
2 |
|
3 | import * as React from 'react';
|
4 | import useLazyRef from '@mui/utils/useLazyRef';
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | export class LazyRipple {
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | static create() {
|
21 | return new LazyRipple();
|
22 | }
|
23 | static use() {
|
24 |
|
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 |
|
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 |
|
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 | }
|
72 | export default function useLazyRipple() {
|
73 | return LazyRipple.use();
|
74 | }
|
75 | function 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 |