Skip to content

Commit

Permalink
Bug fix for #1064.
Browse files Browse the repository at this point in the history
  • Loading branch information
davidjerleke committed Nov 20, 2024
1 parent 53fddf7 commit a12ff56
Showing 1 changed file with 13 additions and 29 deletions.
42 changes: 13 additions & 29 deletions packages/embla-carousel/src/components/Animations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,26 @@ import { EventStore } from './EventStore'
import { WindowType } from './utils'

export type AnimationsUpdateType = (engine: EngineType) => void
export type AnimationsRenderType = (
engine: EngineType,
lagOffset: number
) => void
export type AnimationsRenderType = (engine: EngineType, alpha: number) => void

export type AnimationsType = {
init: () => void
destroy: () => void
start: () => void
stop: () => void
update: () => void
render: (lagOffset: number) => void
render: (alpha: number) => void
}

export function Animations(
ownerDocument: Document,
ownerWindow: WindowType,
update: () => void,
render: (lagOffset: number) => void
render: (alpha: number) => void
): AnimationsType {
const documentVisibleHandler = EventStore()
const fixedTimeStep = 1000 / 60

let lastTimeStamp: number | null = null
let accumulatedTime = 0
let animationId = 0
Expand All @@ -40,36 +38,21 @@ export function Animations(
documentVisibleHandler.clear()
}

function shouldUpdate(): boolean {
return accumulatedTime >= fixedTimeStep
}

function updateAndRemoveAccumulatedTime(): void {
update()
accumulatedTime -= fixedTimeStep
if (shouldUpdate()) updateAndRemoveAccumulatedTime()
}

function renderWithAlpha(): void {
const alpha = accumulatedTime / fixedTimeStep
render(alpha)
}

function animate(timeStamp: DOMHighResTimeStamp): void {
if (!animationId) return

if (!lastTimeStamp) {
lastTimeStamp = timeStamp
update()
renderWithAlpha()
}
if (!lastTimeStamp) lastTimeStamp = timeStamp

const timeElapsed = timeStamp - lastTimeStamp
lastTimeStamp = timeStamp
accumulatedTime += timeElapsed

if (shouldUpdate()) updateAndRemoveAccumulatedTime()
renderWithAlpha()
while (accumulatedTime >= fixedTimeStep) {
update()
accumulatedTime -= fixedTimeStep
}

const alpha = accumulatedTime / fixedTimeStep
render(alpha)

if (animationId) {
animationId = ownerWindow.requestAnimationFrame(animate)
Expand All @@ -78,6 +61,7 @@ export function Animations(

function start(): void {
if (animationId) return

animationId = ownerWindow.requestAnimationFrame(animate)
}

Expand Down

0 comments on commit a12ff56

Please sign in to comment.