Created
May 31, 2020 23:37
-
-
Save IanSSenne/697e6ff00b9401e76f91575b3ba7ad84 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { useState, useEffect, useRef } from "react"; | |
| export function createAnimation(frames) { | |
| let frameTotal = 0; | |
| frames = frames.map((frame, index) => { | |
| frame.duration = frame.duration || 0; | |
| frameTotal += frame.duration; | |
| return frame; | |
| }).map(frame => { | |
| frame.duration /= frameTotal; | |
| return frame; | |
| }); | |
| const Animation = function Animation({ children, duration }) { | |
| var [duration, setDuration] = useState(duration || 1); | |
| const [currentStylesIndex, setCurrentStylesIndex] = useState(0); | |
| let current = { ...frames[currentStylesIndex] }; | |
| current.transition = (frames[currentStylesIndex].duration * duration) + "s"; | |
| useEffect(() => { | |
| if (frames[currentStylesIndex + 1]) { | |
| setTimeout(() => { | |
| setCurrentStylesIndex(currentStylesIndex + 1); | |
| }, frames[currentStylesIndex].duration * duration * 1000); | |
| } | |
| }, [currentStylesIndex]) | |
| delete current.duration; | |
| return (<div style={current}> | |
| {children} | |
| </div>); | |
| } | |
| Animation.on = (Component) => { | |
| return (props) => { | |
| const [duration, setDuration] = useState(props.duration || 1); | |
| const [triggered, Trigger] = useState(false); | |
| const [currentStylesIndex, setCurrentStylesIndex] = useState(0); | |
| const trigger = (value = 1) => { | |
| Trigger(true); | |
| setDuration(value); | |
| } | |
| useEffect(() => { | |
| if (triggered) { | |
| setCurrentStylesIndex(currentStylesIndex + 1); | |
| } | |
| }, [triggered]); | |
| let current = { ...frames[currentStylesIndex] }; | |
| if (triggered) { | |
| current.transition = (frames[currentStylesIndex].duration * duration) + "s"; | |
| if (frames[currentStylesIndex + 1]) { | |
| setTimeout(() => { | |
| setCurrentStylesIndex(currentStylesIndex + 1); | |
| }, frames[currentStylesIndex].duration * duration * 1000); | |
| } | |
| } | |
| delete current.duration; | |
| return (<div style={current}> | |
| <Component trigger={trigger} {...props}></Component> | |
| </div>); | |
| } | |
| } | |
| return Animation; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment