|
| 1 | +import { DIRECTION } from "./types"; |
| 2 | + |
| 3 | +type organizeOptions = { |
| 4 | + from?: number; |
| 5 | + to: number; |
| 6 | + duration?: number; |
| 7 | + delay?: number; |
| 8 | + delayOnce?: boolean; |
| 9 | + repeat?: number; |
| 10 | + direction?: keyof typeof DIRECTION; |
| 11 | + ease?: (x: number) => number; |
| 12 | +}; |
| 13 | + |
| 14 | +/** |
| 15 | + * - A helper function to organize the options for the animation. |
| 16 | + * @param ob - options: `{name: {from: number, to: number, ...}, ...}` |
| 17 | + * @param defaults - changes the default values for each option. |
| 18 | + */ |
| 19 | +export function organize<T extends { [key in keyof T]: organizeOptions }>(ob: T, defaults: Omit<organizeOptions, 'to'> = {}) { |
| 20 | + defaults.from ??= 0; |
| 21 | + defaults.duration ??= 350; |
| 22 | + defaults.delay ??= 0; |
| 23 | + defaults.delayOnce ??= false; |
| 24 | + defaults.repeat ??= 0; |
| 25 | + defaults.direction ??= 'normal'; |
| 26 | + defaults.ease ??= x => x; |
| 27 | + |
| 28 | + const ent = Object.entries<organizeOptions>(ob), |
| 29 | + from = ent.map(e => e[1].from ?? defaults.from), |
| 30 | + to = ent.map(e => e[1].to), |
| 31 | + duration = ent.map(e => e[1].duration ?? defaults.duration), |
| 32 | + delay = ent.map(e => e[1].delay ?? defaults.delay), |
| 33 | + delayOnce = ent.map(e => e[1].delayOnce ?? defaults.delayOnce), |
| 34 | + repeat = ent.map(e => e[1].repeat ?? defaults.repeat), |
| 35 | + direction = ent.map(e => e[1].direction ?? defaults.direction), |
| 36 | + ease = ent.map(e => e[1].ease ?? defaults.ease), |
| 37 | + names = Object.keys(ob) as (keyof T)[]; |
| 38 | + |
| 39 | + const get = (animareArray: number[]) => { |
| 40 | + const res: Record<keyof T, number> = Object.create(null); |
| 41 | + for (let i = 0; i < animareArray.length; i++) res[names[i]] = animareArray[i]; |
| 42 | + return res; |
| 43 | + }; |
| 44 | + |
| 45 | + const patch = (patchOb?: Partial<T>) => organize(Object.assign({}, ob, patchOb)); |
| 46 | + |
| 47 | + return { |
| 48 | + from, |
| 49 | + to, |
| 50 | + duration, |
| 51 | + delay, |
| 52 | + delayOnce, |
| 53 | + repeat, |
| 54 | + direction, |
| 55 | + ease, |
| 56 | + /** |
| 57 | + * - Takes an array of numbers and retruns an object |
| 58 | + * - with the same keys as the original object, but with the values of the array. |
| 59 | + */ |
| 60 | + get, |
| 61 | + /** - Creates a new copy with patched options.*/ |
| 62 | + patch, |
| 63 | + }; |
| 64 | +} |
0 commit comments