From 7e2acb820e2e5f83e3e73f665f1938b3a417a3b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Cchrisshank=E2=80=9D?= Date: Tue, 10 Dec 2024 13:26:37 -0800 Subject: [PATCH] raf refactors --- src/common/client-rect-observer.ts | 13 ++++++------- src/folk-sand.ts | 9 +++++---- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/common/client-rect-observer.ts b/src/common/client-rect-observer.ts index 2518876..0e51bde 100644 --- a/src/common/client-rect-observer.ts +++ b/src/common/client-rect-observer.ts @@ -21,7 +21,7 @@ export class ClientRectObserver { #rootRect = this.#root.getBoundingClientRect(); #entries: ClientRectObserverEntry[] = []; - #rafId = 0; + #rafId = -1; #callback: ClientRectObserverCallback; @@ -48,19 +48,18 @@ export class ClientRectObserver { } }); - #appendEntry(entry: ClientRectObserverEntry) { + async #appendEntry(entry: ClientRectObserverEntry) { + if (this.#entries.length === 0) { + Promise.resolve().then(this.#flush); + } + // deduplicate the same target this.#entries.push(entry); - - if (this.#rafId === 0) { - this.#rafId = requestAnimationFrame(this.#flush); - } } #flush = () => { const entries = this.#entries; this.#entries = []; - this.#rafId = 0; this.#callback(entries, this); }; diff --git a/src/folk-sand.ts b/src/folk-sand.ts index ffb2e44..ffe92e4 100644 --- a/src/folk-sand.ts +++ b/src/folk-sand.ts @@ -9,6 +9,7 @@ import { vertexShader, } from './folk-sand.glsl.ts'; import { FolkShape } from './folk-shape.ts'; +import { requestAnimationFrame } from './common/rAF.ts'; export class FolkSand extends HTMLElement { static tagName = 'folk-sand'; @@ -88,7 +89,7 @@ export class FolkSand extends HTMLElement { this.updateCollisionTexture(); this.attachEventListeners(); - requestAnimationFrame(this.render.bind(this)); + this.render(); } disconnectedCallback() { @@ -365,7 +366,7 @@ export class FolkSand extends HTMLElement { return false; } - private render(time: number) { + private render = (time: number = performance.now()) => { if (this.resizeCanvas()) { this.processResize(); } @@ -378,8 +379,8 @@ export class FolkSand extends HTMLElement { this.pointer.prevX = this.pointer.x; this.pointer.prevY = this.pointer.y; - requestAnimationFrame(this.render.bind(this)); - } + requestAnimationFrame(this.render); + }; private renderPass(time: number) { const gl = this.gl;