File size: 5,240 Bytes
a72140d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use client";
import { animate } from "motion";
import { nanoid } from "nanoid";
import { Application, ApplicationOptions } from "pixi.js";
import { HTMLAttributes, useMemo, useRef } from "react";

import useDebouncedEffect from "@/hooks/useDebouncedEffect";
import { cn } from "@/utils/cn";

import { isDestroyed } from "./utils";

type TickerResult = void;

export type Ticker = ({
  app,
  canvas,
}: {
  app: Application;
  canvas: HTMLCanvasElement;
}) => TickerResult | Promise<TickerResult>;

export interface PixiProps {
  tickers: Ticker[];
  onBeforeInitialized?: (props: { canvas: HTMLCanvasElement }) => void;
  onInitialized?: (props: { canvas: HTMLCanvasElement }) => void;
  canvasAttrs?: HTMLAttributes<HTMLCanvasElement>;
  initOptions?: Partial<ApplicationOptions>;
  fps?: number;
  resolution?: number;
  smartStop?: boolean;
}

export default function Pixi({
  tickers,
  onInitialized,
  onBeforeInitialized,
  canvasAttrs,
  initOptions,
  fps = 60,
  resolution: resolutionFromParams = 1,
  smartStop = true,
}: PixiProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useDebouncedEffect(
    () => {
      const canvas = canvasRef.current!;

      if (!canvas) return;

      const cleanupFunctions: (() => void)[] = [];

      canvas.style.opacity = "0";

      onBeforeInitialized?.({ canvas });

      const resolution = window.devicePixelRatio || 1;

      const app = new Application();

      cleanupFunctions.push(() => {
        if (isDestroyed(app)) return;

        app.destroy(
          {},
          {
            children: true,
            context: true,
            style: true,
          },
        );

        canvas.style.opacity = "0";
      });

      (async () => {
        await app.init({
          canvas: canvas,
          resolution: resolution * resolutionFromParams,
          width: canvas.clientWidth,
          height: canvas.clientHeight,
          antialias: false,
          hello: false,

          autoStart: true,
          sharedTicker: false,
          clearBeforeRender: true,

          eventMode: "passive",

          ...initOptions,
        });

        let tickerCount = 0;
        const originalAdd = app.ticker.add;

        if (fps !== Infinity) {
          app.ticker.maxFPS = fps;
        }

        (app.ticker as any).safeAdd = function (...args: any[]) {
          if (!app.ticker) return undefined as any;

          tickerCount += 1;

          if (tickerCount === 1 && smartStop) startTicker();

          return originalAdd.apply(app.ticker, args as any);
        };

        const originalRemove = app.ticker.remove;

        (app.ticker as any).safeRemove = function (...args: any[]) {
          if (!app.ticker) return undefined as any;

          tickerCount -= 1;

          if (tickerCount === 0 && smartStop) stopTicker();

          return originalRemove.apply(app.ticker, args as any);
        };

        const activeAnimations: ReturnType<typeof animate>[] = [];

        const startTicker = () => {
          app.ticker.start();

          activeAnimations.forEach((animation) => {
            animation.play();
          });
        };

        const stopTicker = () => {
          app.ticker.stop();

          activeAnimations.forEach((animation) => {
            animation.pause();
          });
        };

        (app as any).animate = ((...args: any[]) => {
          const animation = (animate as any)(...args);

          activeAnimations.push(animation);

          animation.finished.then(() => {
            activeAnimations.splice(activeAnimations.indexOf(animation), 1);
          });

          return animation;
        }) as typeof animate;

        for (const ticker of tickers) {
          ticker({
            app,
            canvas,
          });
        }

        app.stage.interactive = false;
        app.stage.cullable = true;
        app.stage.sortableChildren = false;
        app.stage.interactiveChildren = false;

        app.render();

        setTimeout(() => {
          onInitialized?.({ canvas });
          canvas.style.opacity = "1";
        }, 100);

        const observer = new IntersectionObserver(([entry]) => {
          if (entry.isIntersecting) {
            if (tickerCount !== 0 || !smartStop) startTicker();
          } else {
            stopTicker();
          }
        });

        const resizeObserver = new ResizeObserver(() => {
          app.renderer.resize(canvas.clientWidth, canvas.clientHeight);
          app.renderer.render(app.stage);
        });

        observer.observe(canvas);
        resizeObserver.observe(canvas);

        cleanupFunctions.push(() => {
          resizeObserver.disconnect();
          observer.disconnect();
        });
      })();

      return () => {
        cleanupFunctions.forEach((fn) => fn());
      };
    },
    {
      timeout: 1,
      ignoreInitialCall: false,
    },
    [],
  );

  const key = useMemo(() => {
    return nanoid();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tickers]);

  return (
    <canvas
      {...canvasAttrs}
      className={cn(canvasAttrs?.className)}
      key={key}
      ref={canvasRef}
      style={{
        ...canvasAttrs?.style,
        opacity: 0,
      }}
    />
  );
}