diff options
author | Indrajith K L | 2024-02-05 04:15:02 +0530 |
---|---|---|
committer | Indrajith K L | 2024-02-05 04:15:02 +0530 |
commit | f05a472585b2506da21aed71f0252b2d4c04a221 (patch) | |
tree | 4f65a3801f29250a049f3cc5cd2ac9c0a41d78f9 /src/lib/motion/signal.ts | |
download | react-hooks-training-f05a472585b2506da21aed71f0252b2d4c04a221.tar.gz react-hooks-training-f05a472585b2506da21aed71f0252b2d4c04a221.tar.bz2 react-hooks-training-f05a472585b2506da21aed71f0252b2d4c04a221.zip |
React Slides
* Adds useState
* State
* useEffect
* Side Effects
Diffstat (limited to 'src/lib/motion/signal.ts')
-rw-r--r-- | src/lib/motion/signal.ts | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/src/lib/motion/signal.ts b/src/lib/motion/signal.ts new file mode 100644 index 0000000..99697ce --- /dev/null +++ b/src/lib/motion/signal.ts @@ -0,0 +1,61 @@ +import { tweened, type TweenedOptions } from 'svelte/motion' +import { cubicInOut } from 'svelte/easing' +import { interpolate } from 'd3-interpolate' +import type { AnimationFn, Resolve } from './types' + +export function signal<TweenValues>( + values: TweenValues, + options: TweenedOptions<TweenValues> = {} +) { + const { subscribe, update, set } = tweened<TweenValues>(values, { + duration: 1000, + easing: cubicInOut, + interpolate, + ...options, + }) + + let tasks: AnimationFn[] = [] + + function to( + this: any, + values: Partial<TweenValues>, + toOptions: TweenedOptions<TweenValues> = {} + ) { + if (typeof values === 'object') { + tasks.push(() => update((prev) => ({ ...prev, ...values }), toOptions)) + } else { + tasks.push(() => set(values, toOptions)) + } + return this + } + + function reset() { + set(values, { duration: 0 }) + tasks = [] + } + + function sfx(this: any, sound: string, { volume = 0.5 } = {}) { + const audio = new Audio(sound) + audio.volume = volume + + tasks.push(async () => { + audio + .play() + .catch(() => + console.error('To play sounds interact with the page first.') + ) + }) + + return this + } + + async function then(resolve: Resolve) { + for (const task of tasks) { + await task() + } + resolve() + tasks = [] + } + + return { subscribe, to, reset, sfx, then } +} |