From e9c1600f2eabcbcbd03db28ec718e7bb720f5ca1 Mon Sep 17 00:00:00 2001 From: Okiki Date: Tue, 14 Dec 2021 22:07:52 +0000 Subject: [PATCH] fix: make css vars. optional --- packages/animate/src/animate.ts | 158 ++-- packages/animate/src/browser-objects.ts | 26 + packages/animate/src/color-rgba.ts | 250 ++++++ packages/animate/src/colors.ts | 150 ++++ packages/animate/src/css-properties.ts | 66 +- packages/animate/src/css-vars.ts | 19 +- packages/animate/src/custom-easing.ts | 13 +- packages/animate/src/empty-tween.ts | 28 +- packages/animate/src/{api.ts => index.ts} | 3 + packages/animate/src/queue.ts | 16 +- packages/animate/src/stagger-and-random.ts | 10 +- packages/animate/src/types.ts | 927 ++++++++++++--------- packages/animate/src/unit-conversion.ts | 64 +- packages/animate/src/utils.ts | 55 +- 14 files changed, 1236 insertions(+), 549 deletions(-) create mode 100644 packages/animate/src/browser-objects.ts create mode 100644 packages/animate/src/color-rgba.ts create mode 100644 packages/animate/src/colors.ts rename packages/animate/src/{api.ts => index.ts} (78%) diff --git a/packages/animate/src/animate.ts b/packages/animate/src/animate.ts index ba2d35d..e1f034b 100644 --- a/packages/animate/src/animate.ts +++ b/packages/animate/src/animate.ts @@ -5,15 +5,26 @@ import { KeyframeParse, parseOffset } from "./builtin-effects"; import { ParseTransformableCSSProperties, ParseTransformableCSSKeyframes, CSSCamelCase } from "./css-properties"; import { flatten, mapObject, convertToDash, isValid, omit, isObject } from "./utils"; import { createTransformValue, CSSVarSupport, transformCSSVars } from "./css-vars"; +import { getDocument } from "./browser-objects"; import type { TypeEventInput, TypeListenerCallback } from "@okikio/emitter"; -import type { TypeAnimationTarget, TypeAnimationOptionTypes, TypeCallbackArgs, TypeComputedAnimationOptions, IAnimationOptions, TypeComputedOptions, TypeKeyFrameOptionsType, TypeCSSLikeKeyframe, TypeAnimationEvents, TypePlayStates, ICSSProperties } from "./types"; +import type { TypeAnimationTarget, TypeCallbackArgs, IStandaloneComputedAnimateOptions, IStandaloneAnimationConfig, IIndividualTransformProperties, IAnimateInstanceConfig, TypeAnimationEvents, TypePlayStates, ITotalDurationInfo } from "./types"; -/* DOM */ +/** + * Get elements as an array + * @param selector The selector to get the elements from + * @returns An array of elements + */ export const getElements = (selector: string | Node): Node[] => { - return typeof selector === "string" ? Array.from(document.querySelectorAll(selector as string)) : [selector]; + return typeof selector === "string" ? Array.from(getDocument()?.querySelectorAll?.(selector as string)) : [selector]; }; +/** + * Retrieves all target elements + * + * @param targets targets to retrieve, ranging from strings to arrays to DOM Elements + * @returns Returns a flattened array with all the target to retrieve + */ export const getTargets = (targets: TypeAnimationTarget): Node[] => { if (Array.isArray(targets)) { return flatten((targets as TypeAnimationTarget[]).map(getTargets)); @@ -25,15 +36,31 @@ export const getTargets = (targets: TypeAnimationTarget): Node[] => { return []; }; -/* VALUES */ -export const computeOption = (value: TypeAnimationOptionTypes, args: TypeCallbackArgs, context: Animate): TypeComputedAnimationOptions => { +/** + * Computes values. + * If the input value is a function, run it with the arguments from `args`, and the scope from `scope`, then return the computed value. + * Otherwise, return the input value. + * + * @param value The value to compute + * @param args If value is a function, the arguments to pass to said function + * @param scope The scope of the function + * @returns Returns the computed value if inputed value is a function, otherwise, returns the inputed value + */ +export const computeOption = (value: unknown, args: TypeCallbackArgs, scope: Animate): unknown => { if (typeof value === "function") { - return value.apply(context, args); + return value.apply(scope, args); } else return value; }; -export const mapAnimationOptions = (options: IAnimationOptions, args: TypeCallbackArgs, animate: Animate): TypeComputedOptions => { - return mapObject(options, (value) => computeOption(value, args, animate)); +/** + * Loops through animation options and computes the values of each option if the option is a function. + * @param options The computable options to compute + * @param args The arguments to pass to the computable options, callback function + * @param scope The scope of the computable options + * @returns The computed values of computable options + */ +export const mapAnimationOptions = (options: IAnimateInstanceConfig, args: TypeCallbackArgs, scope: Animate): IStandaloneComputedAnimateOptions & Omit => { + return mapObject(options, (value) => computeOption(value, args, scope)); }; /** @@ -146,10 +173,10 @@ export const EasingKeys = Object.keys(EASINGS); /** * Converts users input into a usable easing function string * - * @param ease - easing functions; {@link EasingKeys}, cubic-bezier, steps, linear, etc... + * @param ease easing functions; {@link EasingKeys}, cubic-bezier, steps, linear, etc... * @returns an easing function that `KeyframeEffect` can accept */ -export const GetEase = (ease: keyof typeof EASINGS | string = "ease"): string => { +export const GetEase = (ease: keyof typeof EASINGS | (string & {}) = "ease"): string => { // Convert camelCase strings into dashed strings, then Remove the "ease-" keyword let search = convertToDash(ease).replace(/^ease-/, ""); return EasingKeys.includes(search) ? EASINGS[search] : ease; @@ -180,7 +207,7 @@ export const GetEase = (ease: keyof typeof EASINGS | string = "ease"): string => * } * ``` */ -export const DefaultAnimationOptions: IAnimationOptions = { +export const DefaultAnimationOptions: IAnimateInstanceConfig = { keyframes: [], offset: [], @@ -198,20 +225,31 @@ export const DefaultAnimationOptions: IAnimationOptions = { direction: "normal", padEndDelay: false, - timeline: document.timeline, + timeline: getDocument()?.timeline, extend: {} }; /** Parses the different ways to define options, and returns a merged options object */ -export const parseOptions = (options: IAnimationOptions): IAnimationOptions => { +export const parseOptions = (options: IAnimateInstanceConfig): IAnimateInstanceConfig => { let { options: animation, ...rest } = options; let oldOptions = animation instanceof Animate ? animation.options : (Array.isArray(animation) ? animation?.[0]?.options : animation); return Object.assign({}, oldOptions, rest); } -export const FUNCTION_SUPPORTED_TIMING_KEYS = ["easing", "loop", "endDelay", "duration", "speed", "delay", "timelineOffset", "direction", "extend", "fillMode", "composite"]; -export const NOT_FUNCTION_SUPPORTED_TIMING_KEYS = ["keyframes", "padEndDelay", "persist", "onfinish", "oncancel", "autoplay", "target", "targets", "timeline"]; -export const ALL_TIMING_KEYS = [...FUNCTION_SUPPORTED_TIMING_KEYS, ...NOT_FUNCTION_SUPPORTED_TIMING_KEYS]; +/** + * The array of properties that can be computed as callback functions +*/ +export const FUNCTION_SUPPORTED_ANIMATION_CONFIG_KEYS = ["easing", "loop", "endDelay", "duration", "speed", "delay", "timelineOffset", "direction", "extend", "fillMode", "composite"]; + +/** + * The array of properties that `can't` be computed as callback functions +*/ +export const NON_FUNCTION_SUPPORTED_ANIMATION_CONFIG_KEYS = ["keyframes", "padEndDelay", "persist", "onfinish", "oncancel", "autoplay", "target", "targets", "timeline"]; + +/** + * The full array of properties that are supported as config options, computable or not + */ +export const ALL_ANIMATION_CONFIG_KEYS = [...FUNCTION_SUPPORTED_ANIMATION_CONFIG_KEYS, ...NON_FUNCTION_SUPPORTED_ANIMATION_CONFIG_KEYS]; /** * An animation library for the modern web, which. Inspired by animate plus, and animejs, [@okikio/animate](https://www.skypack.dev/view/@okikio/animate) is a Javascript animation library focused on performance and ease of use. @@ -224,12 +262,12 @@ export class Animate { * * Read more about the {@link DefaultAnimationOptions} */ - public options: IAnimationOptions = {}; + public options: IAnimateInstanceConfig = {}; /** * Stores the options for the current animation `without` the {@link DefaultAnimationOptions} */ - public initialOptions: IAnimationOptions = {}; + public initialOptions: IAnimateInstanceConfig = {}; /** * The properties to animate @@ -244,7 +282,7 @@ export class Animate { /** * The computed options that are used for the total duration */ - public totalDurationOptions: TypeComputedOptions = {}; + public totalDurationOptions: ITotalDurationInfo = {}; /** * The largest duration out of all Animation's @@ -320,7 +358,7 @@ export class Animate { * * _**Note**: keyframes are not included, both the array form and the object form; the options, speed, extend, padEndDelay, and autoplay animation options are not included_ */ - public computedOptions: WeakMap = new WeakMap(); + public computedOptions: WeakMap = new WeakMap(); /** * A WeakMap of Animations @@ -334,8 +372,9 @@ export class Animate { * * _**Note**: the computedKeyframes are changed to their proper Animation instance options, so, some of the names are different, and options that can't be computed are not present. E.g. translateX, skew, etc..., they've all been turned into the transform property.*_ */ - public computedKeyframes: WeakMap = new WeakMap(); - constructor(options: IAnimationOptions = {}) { + public computedKeyframes: WeakMap = new WeakMap(); + + constructor(options: IAnimateInstanceConfig = {}) { this.loop = this.loop.bind(this); this.onVisibilityChange = this.onVisibilityChange.bind(this); this.on("error", console.error); @@ -344,7 +383,7 @@ export class Animate { if (this.mainAnimation) { this.visibilityPlayState = this.getPlayState(); if (Animate.pauseOnPageHidden) { - document.addEventListener('visibilitychange', this.onVisibilityChange, false); + getDocument()?.addEventListener('visibilitychange', this.onVisibilityChange, false); } } @@ -438,7 +477,7 @@ export class Animate { * document `visibilitychange` event handler */ public onVisibilityChange() { - if (document.hidden) { + if (getDocument()?.hidden) { this.visibilityPlayState = this.getPlayState(); if (this.is("running")) { this.loop(); @@ -636,7 +675,7 @@ export class Animate { public stop() { this.cancel(); this.stopLoop(); - document.removeEventListener('visibilitychange', this.onVisibilityChange, false); + getDocument()?.removeEventListener('visibilitychange', this.onVisibilityChange, false); this.targets.forEach((target: HTMLElement) => this.removeTarget(target)); @@ -671,7 +710,7 @@ export class Animate { * Returns the timings of an Animation, given a target * E.g. { duration, endDelay, delay, iterations, iterationStart, direction, easing, fill, etc... } */ - public getTiming(target: HTMLElement): TypeComputedAnimationOptions { + public getTiming(target: HTMLElement): KeyframeEffectOptions { let keyframeOptions = this.computedOptions.get(target) ?? {}; let timings = this.keyframeEffects.get(target).getTiming?.() ?? {}; @@ -734,12 +773,15 @@ export class Animate { /** * Set the playback speed of an Animation */ - public setSpeed(speed: number = 1) { - this.maxSpeed = speed; + public setSpeed(speed: number | string = 1) { + if (typeof speed == "string") + speed = Number(speed); + + this.maxSpeed = speed as number; this.all(anim => { if (anim.updatePlaybackRate) - anim.updatePlaybackRate(speed); - else anim.playbackRate = speed; + anim.updatePlaybackRate(speed as number); + else anim.playbackRate = speed as number; }); return this; } @@ -747,8 +789,14 @@ export class Animate { /** * Returns an array of computed options */ - protected createArrayOfComputedOptions(optionsFromParam: IAnimationOptions, len: number) { - let result: TypeComputedAnimationOptions = []; + protected createArrayOfComputedOptions(optionsFromParam: IAnimateInstanceConfig, len: number) { + let result: (ReturnType & { + /** + * The temporary storage of a specific animations total duration + */ + tempDurations?: number, + iterations?: KeyframeEffectOptions["iterations"] | number + })[] = []; // Converts animation options to their proper Animation Effects forms let convertOptions = (getOption: Function) => { @@ -796,7 +844,7 @@ export class Animate { this.targets.forEach((target: HTMLElement, i) => { // Basically if there is already a computedOption for the target element use it, but don't ovveride any new options - let oldComputedOptions = (this.computedOptions.get(target) ?? {}) as IAnimationOptions; + let oldComputedOptions = (this.computedOptions.get(target) ?? {}) as IAnimateInstanceConfig; let animationOptions = convertOptions((key: string) => { let computedKey = key; if (key == "loop") computedKey = "iterations"; @@ -806,12 +854,13 @@ export class Animate { // Allows the use of functions as the values, for both the keyframes and the animation object // It adds the capability of advanced stagger animation, similar to the animejs stagger functions - let computedOptions = mapAnimationOptions(animationOptions as IAnimationOptions, [i, len, target], this); + let computedOptions = mapAnimationOptions(animationOptions as IAnimateInstanceConfig, [i, len, target], this); if (typeof computedOptions.easing == "string" || Array.isArray(computedOptions.easing)) { let { easing } = computedOptions; - computedOptions.easing = (Array.isArray(easing) ? (easing as string[]).map(ease => GetEase(ease)) : GetEase(easing)); + computedOptions.easing = (Array.isArray(easing) ? (easing as string[]).map(ease => GetEase(ease)) : GetEase(easing)) as IStandaloneAnimationConfig["easing"]; } + // @ts-ignore if (computedOptions.iterations === true) computedOptions.iterations = Infinity; @@ -873,6 +922,11 @@ export class Animate { return result; } + /** + * Specifies if animations should use CSS variables, as CSS variables are not hardware accelerated + */ + public static USE_CSS_VARS = false; + /** * Creates animations out of an array of computed options */ @@ -904,12 +958,12 @@ export class Animate { } let computedKeyframes: Keyframe[] | PropertyIndexedKeyframes; - let animationKeyframe: TypeKeyFrameOptionsType; + let animationKeyframe: Keyframe[] | PropertyIndexedKeyframes; // Accept keyframes as a keyframes Object, or a method, // if there are no animations in the keyframes array, // uses css properties from the options object - let arrKeyframes = keyframes as (Keyframe[] | TypeCSSLikeKeyframe); + let arrKeyframes = keyframes as (Keyframe[] | PropertyIndexedKeyframes); if (isObject(arrKeyframes)) arrKeyframes = KeyframeParse(arrKeyframes); // If `computedKeyframes` have been previously computed for this target element replace @@ -932,7 +986,7 @@ export class Animate { if (!Array.isArray(animationKeyframe)) { // Remove `keyframes` animation option, it's not a valid CSS property - let remaining: IAnimationOptions = omit(["keyframes"], animationKeyframe); + let remaining: IAnimateInstanceConfig = omit(["keyframes"], animationKeyframe); let { offset, ...CSSProperties } = mapAnimationOptions(remaining, [i, len, target], this); // Convert dashed case properties to camelCase, then create a transform CSS value with CSS Vars. as transform functions, @@ -943,12 +997,12 @@ export class Animate { // for transform we parse the translate, skew, scale, and perspective functions (including all their varients) as CSS properties; // it then turns these properties into valid `PropertyIndexedKeyframes` // Read the documentation for `ParseTransformableCSSProperties` - CSSProperties = ParseTransformableCSSProperties(CSSProperties as ICSSProperties); + let TransformedCSSProperties = ParseTransformableCSSProperties((CSSProperties as any) as Keyframe, Animate.USE_CSS_VARS); - let _offset = offset as (string | number)[]; + let _offset = offset as IStandaloneComputedAnimateOptions["offset"]; computedKeyframes = Object.assign({}, - CSSProperties, - isValid(_offset) ? { offset: _offset.map(parseOffset) } : null + TransformedCSSProperties, + isValid(_offset) ? { offset: _offset.map(v => parseOffset(v)) } : null ) as PropertyIndexedKeyframes; } else { computedKeyframes = animationKeyframe.map((keyframe: Keyframe) => { @@ -967,7 +1021,7 @@ export class Animate { transformValue = createTransformValue(transformCSSVars); // Transform transformable CSS properties in each keyframe of the keyframe array - computedKeyframes = ParseTransformableCSSKeyframes(computedKeyframes) as Keyframe[]; + computedKeyframes = ParseTransformableCSSKeyframes(computedKeyframes, Animate.USE_CSS_VARS) as Keyframe[]; } let animation: Animation, keyFrameEffect: KeyframeEffect; @@ -987,6 +1041,7 @@ export class Animate { this.animations.set(keyFrameEffect, animation); } + if (typeof speed == "string") speed = Number(speed); if (animation.updatePlaybackRate) animation.updatePlaybackRate(speed); else animation.playbackRate = speed; @@ -1016,8 +1071,9 @@ export class Animate { }; // To avoid bugs, we manually apply the transform property from the computed CSS properties if CSS Vars are supported - if (CSSVarSupport) - Object.assign(target.style, { transform: transformValue }); + // Note: CSS vars. are not hardware accelerated, so you must really need the flexibility of CSS Vars. before using them + if (CSSVarSupport && Animate.USE_CSS_VARS) + Object.assign(target?.style, { transform: transformValue }); // Set the calculated options & keyframes for each individual animation this.computedOptions.set(target, computedOptions); @@ -1030,7 +1086,7 @@ export class Animate { * * _**Note**: `KeyframeEffect` support is really low, so, I am suggest that you avoid using the `updateOptions` method, until browser support for `KeyframeEffect.updateTiming(...)` and `KeyframeEffefct.setKeyframes(...)` is better_ */ - public updateOptions(options: IAnimationOptions = {}) { + public updateOptions(options: IAnimateInstanceConfig = {}) { try { let optionsFromParam = parseOptions(options); this.initialOptions = optionsFromParam; @@ -1054,10 +1110,10 @@ export class Animate { * Theses are the CSS properties to be animated as Keyframes */ ...oldCSSProperties - } = omit(FUNCTION_SUPPORTED_TIMING_KEYS, this.options); + } = omit(FUNCTION_SUPPORTED_ANIMATION_CONFIG_KEYS, this.options); // This removes all none CSS properties from `optionsFromParam` - this.properties = omit(ALL_TIMING_KEYS, optionsFromParam); + this.properties = omit(ALL_ANIMATION_CONFIG_KEYS, optionsFromParam); // Avoid duplicate elements let oldTargets = this.targets.values(); @@ -1240,13 +1296,13 @@ export class Animate { /** * Call all listeners within an event */ - public emit(events: TypeAnimationEvents[] | TypeAnimationEvents | string | any[], ...args: any) { + public emit(events: TypeAnimationEvents[] | TypeAnimationEvents | (string & {})[] | (string & {}), ...args: any) { this.emitter?.emit?.(events, ...args); return this; } /** Returns the Animate options, as JSON */ - public toJSON(): IAnimationOptions { + public toJSON(): IAnimateInstanceConfig { return this.options; } @@ -1345,7 +1401,7 @@ export class Animate { * * @packageDocumentation */ -export const animate = (options: IAnimationOptions = {}) => { +export const animate = (options: IAnimateInstanceConfig = {}) => { return new Animate(options); }; diff --git a/packages/animate/src/browser-objects.ts b/packages/animate/src/browser-objects.ts new file mode 100644 index 0000000..253bf28 --- /dev/null +++ b/packages/animate/src/browser-objects.ts @@ -0,0 +1,26 @@ +/** + * Returns browser objects that can be used on the server + * @returns An object with the following properties: `{ document, CSS }`, this so `@okikio/animate` can be used in both the browser and the server + */ + export const getBrowserObject = () => { + return { + document: (("document" in globalThis) ? globalThis.document : {}) as Document, + CSS: (("CSS" in globalThis) ? globalThis.CSS : {}) as typeof CSS, + }; +} + +/** + * Returns the browser's `document` object, except if it's a server, in which case it returns an empty object + * @returns The browser document object, but allows it to be used both in the browser and the server + */ +export const getDocument = () => { + return getBrowserObject().document; +} + +/** + * The browser's `CSS` object, except if it's a server, in which case it returns an empty object + * @returns The browser CSS object, except if it's a server, in which case it returns an empty object + */ +export const getCSS = () => { + return getBrowserObject().CSS; +} \ No newline at end of file diff --git a/packages/animate/src/color-rgba.ts b/packages/animate/src/color-rgba.ts new file mode 100644 index 0000000..db68041 --- /dev/null +++ b/packages/animate/src/color-rgba.ts @@ -0,0 +1,250 @@ +/** + * Based on color-rgba https://github.com/colorjs/color-rgba + */ +import names from './colors'; + +export const hsl = { + name: 'hsl', + min: [0, 0, 0], + max: [360, 100, 100], + channel: ['hue', 'saturation', 'lightness'], + alias: ['HSL'], + + rgb: function (hsl) { + var h = hsl[0] / 360, + s = hsl[1] / 100, + l = hsl[2] / 100, + t1, t2, t3, rgb, val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } + else { + t2 = l + s - l * s; + } + t1 = 2 * l - t2; + + rgb = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * - (i - 1); + if (t3 < 0) { + t3++; + } + else if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } + else if (2 * t3 < 1) { + val = t2; + } + else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } + else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; + } +}; + + +/** + * Base hues + * http://dev.w3.org/csswg/css-color/#typedef-named-hue + */ +//FIXME: use external hue detector +var baseHues = { + red: 0, + orange: 60, + yellow: 120, + green: 180, + blue: 240, + purple: 300 +} + +/** + * Parse color from the string passed + * + * @return {Object} A space indicator `space`, an array `values` and `alpha` + */ +export const parse = (cstr) => { + var m, parts = [], alpha = 1, space + if (typeof cstr === 'string') { + //keyword + if (names[cstr]) { + parts = names[cstr].slice() + space = 'rgb' + } + + //reserved words + else if (cstr === 'transparent') { + alpha = 0 + space = 'rgb' + parts = [0, 0, 0] + } + + //hex + else if (/^#[A-Fa-f0-9]+$/.test(cstr)) { + var base = cstr.slice(1) + var size = base.length + var isShort = size <= 4 + alpha = 1 + + if (isShort) { + parts = [ + parseInt(base[0] + base[0], 16), + parseInt(base[1] + base[1], 16), + parseInt(base[2] + base[2], 16) + ] + if (size === 4) { + alpha = parseInt(base[3] + base[3], 16) / 255 + } + } + else { + parts = [ + parseInt(base[0] + base[1], 16), + parseInt(base[2] + base[3], 16), + parseInt(base[4] + base[5], 16) + ] + if (size === 8) { + alpha = parseInt(base[6] + base[7], 16) / 255 + } + } + + if (!parts[0]) parts[0] = 0 + if (!parts[1]) parts[1] = 0 + if (!parts[2]) parts[2] = 0 + + space = 'rgb' + } + + //color space + else if (m = /^((?:rgb|hs[lvb]|hwb|cmyk?|xy[zy]|gray|lab|lchu?v?|[ly]uv|lms)a?)\s*\(([^\)]*)\)/.exec(cstr)) { + var name = m[1] + var isRGB = name === 'rgb' + var base: string = name.replace(/a$/, ''); + space = base + var size = base === 'cmyk' ? 4 : base === 'gray' ? 1 : 3 + parts = m[2].trim() + .split(/\s*[,\/]\s*|\s+/) + .map(function (x, i) { + // + if (/%$/.test(x)) { + //alpha + if (i === size) return parseFloat(x) / 100 + //rgb + if (base === 'rgb') return parseFloat(x) * 255 / 100 + return parseFloat(x) + } + //hue + else if (base[i] === 'h') { + // + if (/deg$/.test(x)) { + return parseFloat(x) + } + // + else if (baseHues[x] !== undefined) { + return baseHues[x] + } + } + return parseFloat(x) + }) + + if (name === base) parts.push(1) + alpha = (isRGB) ? 1 : (parts[size] === undefined) ? 1 : parts[size] + parts = parts.slice(0, size) + } + + //named channels case + else if (cstr.length > 10 && /[0-9](?:\s|\/)/.test(cstr)) { + parts = cstr.match(/([0-9]+)/g).map(function (value) { + return parseFloat(value) + }) + + space = cstr.match(/([a-z])/ig).join('').toLowerCase() + } + } + + //numeric case + else if (!Number.isNaN(cstr)) { + space = 'rgb' + parts = [cstr >>> 16, (cstr & 0x00ff00) >>> 8, cstr & 0x0000ff] + } + + //array-like + else if (Array.isArray(cstr) || cstr.length) { + parts = [cstr[0], cstr[1], cstr[2]] + space = 'rgb' + alpha = cstr.length === 4 ? cstr[3] : 1 + } + + //object case - detects css cases of rgb and hsl + else if (cstr instanceof Object) { + if (cstr.r != null || cstr.red != null || cstr.R != null) { + space = 'rgb' + parts = [ + cstr.r || cstr.red || cstr.R || 0, + cstr.g || cstr.green || cstr.G || 0, + cstr.b || cstr.blue || cstr.B || 0 + ] + } + else { + space = 'hsl' + parts = [ + cstr.h || cstr.hue || cstr.H || 0, + cstr.s || cstr.saturation || cstr.S || 0, + cstr.l || cstr.lightness || cstr.L || cstr.b || cstr.brightness + ] + } + + alpha = cstr.a || cstr.alpha || cstr.opacity || 1 + + if (cstr.opacity != null) alpha /= 100 + } + + return { + space: space, + values: parts, + alpha: alpha + } +} + +export const rgba = (color) => { + // template literals + // @ts-ignore + if (Array.isArray(color) && color.raw) color = String.raw(...arguments) + + var values, i, l + + //attempt to parse non-array arguments + var parsed = parse(color) + + if (!parsed.space) return [] + + values = Array(3) + values[0] = Math.min(Math.max(parsed.values[0], 0), 255) + values[1] = Math.min(Math.max(parsed.values[1], 0), 255) + values[2] = Math.min(Math.max(parsed.values[2], 0), 255) + + if (parsed.space[0] === 'h') { + values = hsl.rgb(values) + } + + values.push(Math.min(Math.max(parsed.alpha, 0), 1)) + + return values +} + +export default rgba; \ No newline at end of file diff --git a/packages/animate/src/colors.ts b/packages/animate/src/colors.ts new file mode 100644 index 0000000..6633dd9 --- /dev/null +++ b/packages/animate/src/colors.ts @@ -0,0 +1,150 @@ +export default { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; \ No newline at end of file diff --git a/packages/animate/src/css-properties.ts b/packages/animate/src/css-properties.ts index 5c0f1ac..b83ab77 100644 --- a/packages/animate/src/css-properties.ts +++ b/packages/animate/src/css-properties.ts @@ -1,12 +1,13 @@ import { CSSArrValue, UnitPX, UnitPXCSSValue, UnitDEG, UnitLess, UnitDEGCSSValue, UnitLessCSSValue } from "./unit-conversion"; -import { camelCase, convertToDash, isValid, mapObject, omit, toStr, transpose, trim } from "./utils"; +import { camelCase, convertToDash, isEmpty, isValid, mapObject, omit, toStr, transpose, trim } from "./utils"; import { CSSVarSupport, toCSSVars, transformProperyNames } from "./css-vars"; import { interpolateString } from "./custom-easing"; +import { getCSS } from "./browser-objects"; -import type { TypeSingleValueCSSProperty, ICSSComputedTransformableProperties, ICSSProperties } from "./types"; +import type { TypeCSSGenericPropertyKeyframes, IIndividualTransformProperties, IComputableCSSProperties, IAllSupportedCSSProperties } from "./types"; export interface ITransformFunctions { - [key: string]: (value: TypeSingleValueCSSProperty | Array) => TypeSingleValueCSSProperty | Array; + [key: string]: (value: TypeCSSGenericPropertyKeyframes | Array) => TypeCSSGenericPropertyKeyframes | Array; } /** @@ -15,27 +16,27 @@ export interface ITransformFunctions { export const TransformFunctions: ITransformFunctions = { "translate": value => CSSArrValue(value, UnitPX), "translate3d": value => CSSArrValue(value, UnitPX), - "translateX": (value: TypeSingleValueCSSProperty) => UnitPXCSSValue(value), - "translateY": (value: TypeSingleValueCSSProperty) => UnitPXCSSValue(value), - "translateZ": (value: TypeSingleValueCSSProperty) => UnitPXCSSValue(value), + "translateX": (value: TypeCSSGenericPropertyKeyframes) => UnitPXCSSValue(value), + "translateY": (value: TypeCSSGenericPropertyKeyframes) => UnitPXCSSValue(value), + "translateZ": (value: TypeCSSGenericPropertyKeyframes) => UnitPXCSSValue(value), "rotate": value => CSSArrValue(value, UnitDEG), "rotate3d": value => CSSArrValue(value, UnitLess), - "rotateX": (value: TypeSingleValueCSSProperty) => UnitDEGCSSValue(value), - "rotateY": (value: TypeSingleValueCSSProperty) => UnitDEGCSSValue(value), - "rotateZ": (value: TypeSingleValueCSSProperty) => UnitDEGCSSValue(value), + "rotateX": (value: TypeCSSGenericPropertyKeyframes) => UnitDEGCSSValue(value), + "rotateY": (value: TypeCSSGenericPropertyKeyframes) => UnitDEGCSSValue(value), + "rotateZ": (value: TypeCSSGenericPropertyKeyframes) => UnitDEGCSSValue(value), "scale": value => CSSArrValue(value, UnitLess), "scale3d": value => CSSArrValue(value, UnitLess), - "scaleX": (value: TypeSingleValueCSSProperty) => UnitLessCSSValue(value), - "scaleY": (value: TypeSingleValueCSSProperty) => UnitLessCSSValue(value), - "scaleZ": (value: TypeSingleValueCSSProperty) => UnitLessCSSValue(value), + "scaleX": (value: TypeCSSGenericPropertyKeyframes) => UnitLessCSSValue(value), + "scaleY": (value: TypeCSSGenericPropertyKeyframes) => UnitLessCSSValue(value), + "scaleZ": (value: TypeCSSGenericPropertyKeyframes) => UnitLessCSSValue(value), "skew": value => CSSArrValue(value, UnitDEG), - "skewX": (value: TypeSingleValueCSSProperty) => UnitDEGCSSValue(value), - "skewY": (value: TypeSingleValueCSSProperty) => UnitDEGCSSValue(value), + "skewX": (value: TypeCSSGenericPropertyKeyframes) => UnitDEGCSSValue(value), + "skewY": (value: TypeCSSGenericPropertyKeyframes) => UnitDEGCSSValue(value), - "perspective": (value: TypeSingleValueCSSProperty) => UnitPXCSSValue(value), + "perspective": (value: TypeCSSGenericPropertyKeyframes) => UnitPXCSSValue(value), // "matrix": value => CSSArrValue(value, UnitLess), // "matrix3d": value => CSSArrValue(value, UnitLess), @@ -238,13 +239,13 @@ export const arrFill = (arr: any[] | any[][], maxLen?: number) => { * an object with a properly formatted `transform` and `opactity`, as well as other unformatted CSS properties * ``` */ -export const ParseTransformableCSSProperties = (properties: ICSSProperties): ICSSProperties => { +export const ParseTransformableCSSProperties = (properties: IComputableCSSProperties, USE_CSS_VARS = false): IComputableCSSProperties => { // Convert dash seperated strings to camelCase strings - let AllCSSProperties = CSSCamelCase(properties) as ICSSProperties; - let rest: ICSSProperties; + let AllCSSProperties = CSSCamelCase(properties) as IComputableCSSProperties; + let rest: IComputableCSSProperties; let transform: string[]; - if (CSSVarSupport) { + if (CSSVarSupport && USE_CSS_VARS) { rest = Object.assign({}, omit(transformProperyNames, AllCSSProperties), toCSSVars(AllCSSProperties)); } else { // Adds support for ordered transforms @@ -272,7 +273,7 @@ export const ParseTransformableCSSProperties = (properties: ICSSProperties): ICS if (!/color|shadow/i.test(key)) { let isAngle = /rotate/i.test(key); let isLength = new RegExp(CSSPXDataType, "i").test(key) || - CSS.supports(convertToDash(key), "1px"); + (!isEmpty(getCSS()) && getCSS()?.supports?.(convertToDash(key), "1px")); // There is an intresting bug that occurs if you test a string againt the same instance of a Regular Expression // where the answer will be different every test @@ -314,11 +315,11 @@ export const ParseTransformableCSSProperties = (properties: ICSSProperties): ICS * @returns * an array of keyframes, with transformed CSS properties */ -export const ParseTransformableCSSKeyframes = (keyframes: (ICSSComputedTransformableProperties & Keyframe)[]) => { +export const ParseTransformableCSSKeyframes = (keyframes: (IIndividualTransformProperties & Keyframe)[], USE_CSS_VARS = false) => { return keyframes.map(properties => { // Convert dash seperated strings to camelCase strings - let AllCSSProperties = CSSCamelCase(properties) as ICSSComputedTransformableProperties & ICSSProperties & Keyframe; - if (CSSVarSupport) { + let AllCSSProperties = CSSCamelCase(properties) as IIndividualTransformProperties & Keyframe; + if (CSSVarSupport && USE_CSS_VARS) { return { rest: Object.assign({}, toCSSVars(AllCSSProperties), omit(transformProperyNames, AllCSSProperties)), transformFunctions: null @@ -352,35 +353,34 @@ export const ParseTransformableCSSKeyframes = (keyframes: (ICSSComputedTransform // iterations, // offset, ...rest - } = AllCSSProperties; - translate = UnitPXCSSValue(translate as TypeSingleValueCSSProperty); - translate3d = UnitPXCSSValue(translate3d as TypeSingleValueCSSProperty); + translate = UnitPXCSSValue(translate as TypeCSSGenericPropertyKeyframes); + translate3d = UnitPXCSSValue(translate3d as TypeCSSGenericPropertyKeyframes); translateX = UnitPXCSSValue(translateX)[0]; translateY = UnitPXCSSValue(translateY)[0]; translateZ = UnitPXCSSValue(translateZ)[0]; - rotate = UnitDEGCSSValue(rotate as TypeSingleValueCSSProperty); - rotate3d = UnitLessCSSValue(rotate3d as TypeSingleValueCSSProperty); + rotate = UnitDEGCSSValue(rotate as TypeCSSGenericPropertyKeyframes); + rotate3d = UnitLessCSSValue(rotate3d as TypeCSSGenericPropertyKeyframes); rotateX = UnitDEGCSSValue(rotateX)[0]; rotateY = UnitDEGCSSValue(rotateY)[0]; rotateZ = UnitDEGCSSValue(rotateZ)[0]; - scale = UnitLessCSSValue(scale as TypeSingleValueCSSProperty); - scale3d = UnitLessCSSValue(scale3d as TypeSingleValueCSSProperty); + scale = UnitLessCSSValue(scale as TypeCSSGenericPropertyKeyframes); + scale3d = UnitLessCSSValue(scale3d as TypeCSSGenericPropertyKeyframes); scaleX = UnitLessCSSValue(scaleX)[0]; scaleY = UnitLessCSSValue(scaleY)[0]; scaleZ = UnitLessCSSValue(scaleZ)[0]; - skew = UnitDEGCSSValue(skew as TypeSingleValueCSSProperty); + skew = UnitDEGCSSValue(skew as TypeCSSGenericPropertyKeyframes); skewX = UnitDEGCSSValue(skewX)[0]; skewY = UnitDEGCSSValue(skewY)[0]; perspective = UnitPXCSSValue(perspective)[0]; - // matrix = UnitLessCSSValue(matrix as TypeSingleValueCSSProperty); - // matrix3d = UnitLessCSSValue(matrix3d as TypeSingleValueCSSProperty); + // matrix = UnitLessCSSValue(matrix as TypeCSSGenericPropertyKeyframes); + // matrix3d = UnitLessCSSValue(matrix3d as TypeCSSGenericPropertyKeyframes); return { rest, diff --git a/packages/animate/src/css-vars.ts b/packages/animate/src/css-vars.ts index d60d1e1..dfe2e8d 100644 --- a/packages/animate/src/css-vars.ts +++ b/packages/animate/src/css-vars.ts @@ -1,5 +1,6 @@ import { UnitPXCSSValue, UnitDEGCSSValue } from "./unit-conversion"; -import { isValid, transpose } from "./utils"; +import { isValid, transpose, isEmpty } from "./utils"; +import { getCSS } from "./browser-objects"; export const transformCSSVars = { translate3d: ["--translate3d0", "--translate3d1", "--translate3d2"], @@ -20,7 +21,7 @@ export const transformCSSVars = { scaleY: "--scaleY", scaleZ: "--scaleZ", - // You can choose to use transform functions or matrix's, but not both + // // You can choose to use transform functions or matrix's, but not both // matrix3d: "--matrix3d", // matrix: "--matrix", @@ -31,7 +32,7 @@ export const transformCSSVars = { perspective: "--perspective" }; -export const CSSVarSupport = "registerProperty" in CSS; +export const CSSVarSupport = "registerProperty" in getCSS(); export const transformProperyNames = Object.keys(transformCSSVars); export const createTransformValue = (opts = {}) => { @@ -55,28 +56,28 @@ export const createTransformValue = (opts = {}) => { if (/translate|perspective/i.test(name)) { // @ts-ignore - CSS.registerProperty({ + getCSS()?.registerProperty?.({ ...opts, syntax: "", initialValue: "0px" }); } else if (/rotate3d3|skew/i.test(name)) { // @ts-ignore - CSS.registerProperty({ + getCSS()?.registerProperty?.({ ...opts, syntax: "", initialValue: "0deg" }); } else if (/scale|rotate3d/i.test(name)) { // @ts-ignore - CSS.registerProperty({ + getCSS()?.registerProperty?.({ ...opts, syntax: "", initialValue: /rotate3d/i.test(name) ? 0 : 1 }); } else if (/rotate/i.test(name)) { // @ts-ignore - CSS.registerProperty({ + getCSS()?.registerProperty?.({ ...opts, syntax: "", initialValue: "0deg" @@ -158,8 +159,8 @@ export const toCSSVars = (opts = {}) => { CSSVars.forEach((CSSvariable, i) => { // The first value in scale states both the x and y scales, but only if there is only one value given let index = ScaleBothAxis ? 0 : i; - let value = is2dArray - ? // flip a 2d array over it's diagonal axis, + let value = is2dArray ? + // flip a 2d array over it's diagonal axis, // this ensures the correct CSS axis variable for translate, scale, rotate, and their 3d varitants // (search up "transpose matrix" on Google for more info.) transpose(...input)[index] diff --git a/packages/animate/src/custom-easing.ts b/packages/animate/src/custom-easing.ts index d48e8b4..9d41b0c 100644 --- a/packages/animate/src/custom-easing.ts +++ b/packages/animate/src/custom-easing.ts @@ -6,11 +6,14 @@ import { mapObject, getUnit, trim, + isEmpty } from "./utils"; +import { rgba } from "./color-rgba"; import { toRGBAArr } from "./unit-conversion"; +import { getCSS } from "./browser-objects"; import bezier from "./bezier-easing"; -import type { IAnimationOptions } from "./types"; +import type { IAnimateInstanceConfig } from "./types"; export const limit = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max); @@ -189,7 +192,9 @@ export const EaseOutIn = (ease: TypeEasingFunction): TypeEasingFunction => { }; /** - * The default list of easing functions, do note this is different from {@link EASING} + * The default list of easing functions, + * + * _**Note**_: this is different from {@link EASING} */ export const EasingFunctions: { [key: string]: TypeEasingFunction } = { steps: Steps, @@ -452,7 +457,7 @@ export const interpolateComplex = ( if (isNumber) return interpolateNumber(t, values as number[], decimal); // Interpolate colors - let isColor = values.every((v) => CSS.supports("color", toStr(v))); + let isColor = values.every((v) => !isEmpty(getCSS()) ? getCSS()?.supports?.("color", toStr(v)) : isValid(rgba(v ?? null)) ); if (isColor) return `rgba(${interpolateColor(t, values as string[], decimal)})`; @@ -821,7 +826,7 @@ export const ApplyCustomEasing = ( | TypeEasingFunction | (number | string)[]; } = {} -): IAnimationOptions & TypeCustomEasingOptions & { +): IAnimateInstanceConfig & TypeCustomEasingOptions & { [key: string]: | number | string diff --git a/packages/animate/src/empty-tween.ts b/packages/animate/src/empty-tween.ts index c288020..4712eec 100644 --- a/packages/animate/src/empty-tween.ts +++ b/packages/animate/src/empty-tween.ts @@ -1,10 +1,10 @@ - import { ApplyCustomEasing, ComplexEasingSyntax, EasingFunctionKeys, GetEasingFunction, interpolateComplex } from "./custom-easing"; -import { Animate, parseOptions, ALL_TIMING_KEYS, EasingKeys, GetEase, getTargets } from "./animate"; +import { Animate, parseOptions, ALL_ANIMATION_CONFIG_KEYS, EasingKeys, GetEase, getTargets } from "./animate"; import { pick, omit, mapObject, isValid } from "./utils"; +import { getDocument } from "./browser-objects"; import { Manager } from "@okikio/manager"; -import type { IAnimationOptions } from "./types"; +import type { IAnimateInstanceConfig, IStandaloneComputedAnimateOptions } from "./types"; import type { TypeCustomEasingOptions, TypeEasingFunction } from "./custom-easing"; import type { TypeListenerCallback } from "@okikio/emitter"; @@ -12,7 +12,7 @@ import type { TypeListenerCallback } from "@okikio/emitter"; export let UIDCount = 0; /** For better performance push empty elements into `EmptyTweenElContainer` */ -export const EmptyTweenElContainer: HTMLElement = document.createElement("div"); +export const EmptyTweenElContainer: HTMLElement = getDocument()?.createElement?.("div"); /** Creates a new empty tween element */ export const createEmptyEl = () => { @@ -20,10 +20,10 @@ export const createEmptyEl = () => { EmptyTweenElContainer.id = "empty-tween-el-container"; EmptyTweenElContainer.style.setProperty("display", "none"); EmptyTweenElContainer.style.setProperty("contain", "paint layout size"); - document.body.appendChild(EmptyTweenElContainer); + getDocument()?.body?.appendChild(EmptyTweenElContainer); } - let el = document.createElement("div"); + let el = getDocument()?.createElement?.("div"); el.id = `empty-animate-el-${UIDCount++}`; el.style.setProperty("display", "none"); @@ -46,9 +46,9 @@ export class DestroyableAnimate extends Animate { * - animate the opacity of said element * - You can then use the "update" event to watch for changes in opacity and use the opacity as a progress bar of values between 0 to 1 */ -export const createTweenOptions = (options: IAnimationOptions & TypeCustomEasingOptions = {}): IAnimationOptions => { - let { easing, decimal, numPoints, opacity, ...optionsObj } = parseOptions(options) as IAnimationOptions & TypeCustomEasingOptions; - let AnimationOptions = pick(ALL_TIMING_KEYS, optionsObj) as IAnimationOptions; +export const createTweenOptions = (options: IAnimateInstanceConfig & TypeCustomEasingOptions = {}) => { + let { easing, decimal, numPoints, opacity, ...optionsObj } = parseOptions(options) as IAnimateInstanceConfig & TypeCustomEasingOptions; + let AnimationOptions = pick(ALL_ANIMATION_CONFIG_KEYS, optionsObj) as unknown as IStandaloneComputedAnimateOptions; let EasingFunction = easing as (string | string[] | TypeEasingFunction); if (typeof easing == "string") { @@ -72,7 +72,7 @@ export const createTweenOptions = (options: IAnimationOptions & TypeCustomEasing return { ...opacityObj, ...AnimationOptions - }; + } as unknown as IAnimateInstanceConfig; }; /** @@ -119,14 +119,14 @@ export class AnimateAttributes extends DestroyableAnimate { * Stores all updateListeners for the corresponding tweens, to avoid leaving unused listeners */ public updateListeners = new Manager(); - public updateOptions(options: IAnimationOptions & TypeCustomEasingOptions = {}) { - let optionsObj = parseOptions(options) as IAnimationOptions & TypeCustomEasingOptions; + public updateOptions(options: IAnimateInstanceConfig & TypeCustomEasingOptions = {}) { + let optionsObj = parseOptions(options) as IAnimateInstanceConfig & TypeCustomEasingOptions; let el = this.targets.size > 1 ? null : { target: createEmptyEl() }; let opts = Object.assign({}, createTweenOptions(omit(["target", "targets"], optionsObj)), el); super.updateOptions(opts); - let Properties = omit(ALL_TIMING_KEYS, optionsObj); + let Properties = omit(ALL_ANIMATION_CONFIG_KEYS, optionsObj); try { this.updateListeners = this.updateListeners ?? new Manager() this.updateListeners.forEach((listener, index) => { @@ -172,6 +172,6 @@ export class AnimateAttributes extends DestroyableAnimate { /** * Creates new instances of {@link AnimateAttributes} */ -export const tweenAttr = (options: IAnimationOptions & TypeCustomEasingOptions = {}) => { +export const tweenAttr = (options: IAnimateInstanceConfig & TypeCustomEasingOptions = {}) => { return new AnimateAttributes(options); }; \ No newline at end of file diff --git a/packages/animate/src/api.ts b/packages/animate/src/index.ts similarity index 78% rename from packages/animate/src/api.ts rename to packages/animate/src/index.ts index 299d417..b3448fd 100644 --- a/packages/animate/src/api.ts +++ b/packages/animate/src/index.ts @@ -1,5 +1,8 @@ export * from "./types"; export * from "./utils"; +export * from "./colors"; +export * from "./color-rgba"; +export * from "./browser-objects"; export * from "./builtin-effects"; export * from "./css-properties"; export * from "./unit-conversion"; diff --git a/packages/animate/src/queue.ts b/packages/animate/src/queue.ts index 720874f..64ee586 100644 --- a/packages/animate/src/queue.ts +++ b/packages/animate/src/queue.ts @@ -1,7 +1,7 @@ import { Animate, DefaultAnimationOptions, parseOptions } from "./animate"; import { Manager } from "@okikio/manager"; -import type { IAnimationOptions, TypeAnimationEvents, TypeComputedOptions, TypePlayStates } from "./types"; +import type { IAnimateInstanceConfig, TypeAnimationEvents, TypePlayStates } from "./types"; import type { TypeEventInput, TypeListenerCallback } from "@okikio/emitter"; /** @@ -126,10 +126,10 @@ export class Queue { * The options from the mainInstance */ public get options() { return this.mainInstance.options; } - public set options(opts: IAnimationOptions) { this.mainInstance.options = parseOptions(opts); } + public set options(opts: IAnimateInstanceConfig) { this.mainInstance.options = parseOptions(opts); } /** The initial options set in the constructor */ - public initialOptions: IAnimationOptions = {}; + public initialOptions: IAnimateInstanceConfig = {}; /** * The event emitter of the mainInstance @@ -140,7 +140,7 @@ export class Queue { * The promise created by the mainInstance */ public get promise() { return this.mainInstance.promise; } - constructor(options: IAnimationOptions = {}) { + constructor(options: IAnimateInstanceConfig = {}) { this.mainInstance = new Animate({ duration: 0 }); this.initialOptions = Object.assign({}, DefaultAnimationOptions, parseOptions(options)); @@ -154,9 +154,9 @@ export class Queue { * @param options - you can add an Animate instance by either using animation options or by adding a pre-existing Animate Instance. * @param timelineOffset - by default the timelineOffset is 0, which means the Animation will play in chronological order of when it was defined; a different value, specifies how many miliseconds off from the chronological order before it starts playing the Animation. You can also use absolute values, for exmple, if you want your animation to start at 0ms, setting timelineOffset to 0, or "0" will use relative offsets, while using "= 0" will use absolute offsets. Read more on {@link relativeTo} */ - public add(options: IAnimationOptions | Animate = {}, timelineOffset: string | number = 0) { + public add(options: IAnimateInstanceConfig | Animate = {}, timelineOffset: string | number = 0) { let newInst: Animate; - let insParams: IAnimationOptions = Object.assign({}, DefaultAnimationOptions, this.initialOptions, + let insParams: IAnimateInstanceConfig = Object.assign({}, DefaultAnimationOptions, this.initialOptions, options instanceof Animate ? options.initialOptions : parseOptions(options)); if (Math.abs(this.totalDuration) !== Infinity) { @@ -418,7 +418,7 @@ export class Queue { } /** Returns the Animate options, as JSON */ - public toJSON(): IAnimationOptions { + public toJSON(): IAnimateInstanceConfig { return this.options; } @@ -435,4 +435,4 @@ export class Queue { /** * Creates a new {@link Queue} instance, and passes the options to the constructor */ -export const queue = (options: IAnimationOptions = {}) => new Queue(options); \ No newline at end of file +export const queue = (options: IAnimateInstanceConfig = {}) => new Queue(options); \ No newline at end of file diff --git a/packages/animate/src/stagger-and-random.ts b/packages/animate/src/stagger-and-random.ts index 55a1e3c..0adcdbb 100644 --- a/packages/animate/src/stagger-and-random.ts +++ b/packages/animate/src/stagger-and-random.ts @@ -2,7 +2,7 @@ import { CustomEasing, GetEasingFunction, parseEasingParameters } from "./custom import { getUnit } from "./utils"; import type { TypeEasingFunction, TypeCustomEasingOptions } from "./custom-easing"; -import type { TypeCallback } from "./types"; +import type { TypeComputableAnimationFunction } from "./types"; export interface IStaggerOptions { from?: number | "first" | "center" | "last", @@ -96,7 +96,7 @@ export interface IStaggerOptions { * Because stagger returns an {@link TypeCallback | AnimationOption callback}, it fundementally doesn't work with {@link CustomEasing}, * so, you need to use {@link StaggerCustomEasing} to enable custom easing. */ -export const stagger = (val: string | number | (string | number)[], params: IStaggerOptions = {}): TypeCallback => { +export const stagger = (val: string | number | (string | number)[], params: IStaggerOptions = {}): TypeComputableAnimationFunction => { const { grid, axis, from = 0, easing, direction = "normal" } = params; const isArr = Array.isArray(val); @@ -121,7 +121,7 @@ export const stagger = (val: string | number | (string | number)[], params: ISta let fromIndex = from as number; if (/from/i.test(from as string)) fromIndex = 0; - return (index, total): string | number => { + return (index: number, total: number): string | number => { if (/center/i.test(from as string)) fromIndex = (total - 1) / 2; if (/last/i.test(from as string)) fromIndex = total - 1; @@ -206,10 +206,10 @@ export interface IStaggerCustomEasingOptions extends TypeCustomEasingOptions { * * Check out demos on [Codepen](https://codepen.io/okikio/pen/JjNXGPq) */ -export const StaggerCustomEasing = (val: (string | number)[], params: IStaggerCustomEasingOptions = {}): TypeCallback => { +export const StaggerCustomEasing = (val: (string | number)[], params: IStaggerCustomEasingOptions = {}): TypeComputableAnimationFunction<(string | number)[]> => { let staggerOptions = params.stagger ?? {}; - return (index, total) => { + return (index: number, total: number) => { let staggaredValues = val.map((current, i) => { let prev = val[Math.max(0, i - 1)]; return stagger([prev, current], staggerOptions)(index, total); diff --git a/packages/animate/src/types.ts b/packages/animate/src/types.ts index 19812d5..c41a95d 100644 --- a/packages/animate/src/types.ts +++ b/packages/animate/src/types.ts @@ -1,48 +1,145 @@ -import type { KebabCase, CamelCase, KebabCasedProperties } from "type-fest"; +import type { KebabCasedProperties } from "type-fest"; +import type { Properties, PropertiesHyphen, PropertiesFallback, PropertiesHyphenFallback, Property } from "csstype"; -// Types -export type TypeAnimationTarget = string | Node | NodeList | HTMLCollection | HTMLElement[] | TypeAnimationTarget[]; +import type { EASINGS } from "./animate"; -export type TypeCallbackArgs = [number, number, HTMLElement]; -export type TypeGeneric = boolean | object | string | number; -export type TypeCSSLikeKeyframe = { [key: string]: Keyframe & ICSSComputedTransformableProperties }; -export type TypeKeyFrameOptionsType = TypeCSSLikeKeyframe | Keyframe[] | PropertyIndexedKeyframes; -export type TypeCSSPropertyValue = (string | number)[]; -export type TypeComputedAnimationOptions = TypeGeneric | TypeGeneric[] | TypeKeyFrameOptionsType | KeyframeEffectOptions | ICSSComputedTransformableProperties; -export type TypeCallback = (index?: number, total?: number, element?: HTMLElement) => TypeComputedAnimationOptions; -export type TypeAnimationOptionTypes = TypeCallback | TypeComputedAnimationOptions; -export type TypeComputedOptions = { [key: string]: TypeComputedAnimationOptions }; -export type TypeSingleValueCSSProperty = string | number | TypeCSSPropertyValue; +/** + * The Animation Events supported by @okikio/animate, they are based on the Animation Events supported by WAAPI + * - "begin" - fired when an animation starts + * - "cancel" - fired when an animation is canceled + * - "finish" - fired when an animation is finished + * - "update" - fired at a specified frame rate (default is 60), it is fired by a `requestAnimationFrame` loop + * - "pause" - fired when an animation is paused + * - "play" - fired when an animation is played + * - "error" - fired when an error has occured in setting up the animation (e.g. invalid options, invalid target, browser doesn't support certain features, etc.) + * - "playstate-change" - fired when the play state of an animation changes + */ +export type TypeAnimationEvents = "update" | "play" | "pause" | "begin" | "cancel" | "finish" | "error" | "stop" | "playstate-change"; + +/** + * The various play states of an animation + * - "idle" - The animation is not running + * - "pause" - The animation is paused + * - "running" - The animation is playing + * - "finished" - The animation has finished playing + */ +export type TypePlayStates = "idle" | "running" | "paused" | "finished"; + +/** Lists all supported Animation Targets */ +export type TypeAnimationTarget = string | Node | NodeList | HTMLCollection | HTMLElement[] | TypeAnimationTarget[]; /** - * [Animatable CSS Properties](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties) + * @param index - index of target element + * @param total - total number of target element + * @param element - the target element * + * @returns T +*/ +export type TypeComputableAnimationFunction = (index?: number, total?: number, element?: HTMLElement) => T; + +/** + * The callback parameters for computable animation functions + * e.g. `(index?: number, total?: number, element?: HTMLElement) => number` */ -export type TypeAnimatableCSSProperties = CamelCase<"-webkit-line-clamp" | "-webkit-text-fill-color" | "-webkit-text-stroke" | "-webkit-text-stroke-color" | "all" | "background" | "background-color" | "background-position" | "background-size" | "block-size" | "border" | "border-block-end" | "border-block-end-color" | "border-block-end-width" | "border-block-start" | "border-block-start-color" | "border-block-start-width" | "border-bottom" | "border-bottom-color" | "border-bottom-left-radius" | "border-bottom-right-radius" | "border-bottom-width" | "border-color" | "border-end-end-radius" | "border-end-start-radius" | "border-image-outset" | "border-image-slice" | "border-image-width" | "border-inline-end" | "border-inline-end-color" | "border-inline-end-width" | "border-inline-start" | "border-inline-start-color" | "border-inline-start-width" | "border-left" | "border-left-color" | "border-left-width" | "border-radius" | "border-right" | "border-right-color" | "border-right-width" | "border-start-end-radius" | "border-start-start-radius" | "border-top" | "border-top-color" | "border-top-left-radius" | "border-top-right-radius" | "border-top-width" | "border-width" | "bottom" | "box-shadow" | "caret-color" | "clip" | "clip-path" | "color" | "column-count" | "column-gap" | "column-rule" | "column-rule-color" | "column-rule-width" | "column-width" | "columns" | "filter" | "flex" | "flex-basis" | "flex-grow" | "flex-shrink" | "font" | "font-size" | "font-size-adjust" | "font-stretch" | "font-variation-settings" | "font-weight" | "gap" | "grid-column-gap" | "grid-gap" | "grid-row-gap" | "grid-template-columns" | "grid-template-rows" | "height" | "inline-size" | "inset" | "inset-block" | "inset-block-end" | "inset-block-start" | "inset-inline" | "inset-inline-end" | "inset-inline-start" | "left" | "letter-spacing" | "line-height" | "margin" | "margin-block-end" | "margin-block-start" | "margin-bottom" | "margin-inline-end" | "margin-inline-start" | "margin-left" | "margin-right" | "margin-top" | "mask" | "max-block-size" | "max-height" | "max-inline-size" | "max-width" | "min-block-size" | "min-height" | "min-inline-size" | "min-width" | "object-position" | "offset" | "offset-anchor" | "offset-distance" | "offset-path" | "offset-rotate" | "opacity" | "order" | "outline" | "outline-color" | "outline-offset" | "outline-width" | "padding" | "padding-block-end" | "padding-block-start" | "padding-bottom" | "padding-inline-end" | "padding-inline-start" | "padding-left" | "padding-right" | "padding-top" | "perspective" | "perspective-origin" | "right" | "rotate" | "row-gap" | "scale" | "scroll-margin" | "scroll-margin-block" | "scroll-margin-block-end" | "scroll-margin-block-start" | "scroll-margin-bottom" | "scroll-margin-inline" | "scroll-margin-inline-end" | "scroll-margin-inline-start" | "scroll-margin-left" | "scroll-margin-right" | "scroll-margin-top" | "scroll-padding" | "scroll-padding-block" | "scroll-padding-block-end" | "scroll-padding-block-start" | "scroll-padding-bottom" | "scroll-padding-inline" | "scroll-padding-inline-end" | "scroll-padding-inline-start" | "scroll-padding-left" | "scroll-padding-right" | "scroll-padding-top" | "shape-image-threshold" | "shape-margin" | "shape-outside" | "tab-size" | "text-decoration" | "text-decoration-color" | "text-decoration-thickness" | "text-emphasis" | "text-emphasis-color" | "text-indent" | "text-shadow" | "text-underline-offset" | "top" | "transform" | "transform-origin" | "translate" | "vertical-align" | "visibility" | "width" | "word-spacing" | "z-index" | "opacity">; +export type TypeCallbackArgs = Parameters>; /** - * [SVG Presentation Attributes](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/Presentation) + * string & number generic values for all animation option properties. + * + * The `string & {}` is a typescript hack for autocomplete, + * check out [github.com/microsoft/TypeScript/issues/29729](https://github.com/microsoft/TypeScript/issues/29729) to learn more */ -export type TypeSVGPresentationAttributes = CamelCase<"alignment-baseline" | "baseline-shift" | "clip-rule" | "color-interpolation" | "color-interpolation-filters" | "color-profile" | "color-rendering" | "cursor" | "direction" | "display" | "fill" | "fill-opacity" | "fill-rule" | "flood-color" | "flood-opacity" | "font-family" | "font-style" | "font-variant" | "kerning" | "lighting-color" | "marker-end" | "marker-mid" | "marker-start" | "overflow" | "pointer-events" | "stroke" | "stroke-dasharray" | "stroke-dashoffset" | "stroke-linecap" | "stroke-linejoin" | "stroke-miterlimit" | "stroke-opacity" | "stroke-width" | "text-anchor" | "text-rendering" | "vector-effect" | "writing-mode">; +export type TypeCommonGenerics = number | (string & {}) | `var(--${string})` | `var(--${string}, ${string | number})`; /** - * [SVG Presentation Attributes](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/Presentation) + * string & number generic values for CSS Properties. + * + * The `string & {}` is a typescript hack for autocomplete, + * check out [github.com/microsoft/TypeScript/issues/29729](https://github.com/microsoft/TypeScript/issues/29729) to learn more */ -export type TypeAnimatableSVGAttributes = { - [property in TypeSVGPresentationAttributes]?: TypeAnimationOptionTypes; -}; +export type TypeCommonCSSGenerics = TypeCommonGenerics | `var(--${string})` | `var(--${string}, ${string | number})`; /** - * CSS properties the `ParseTransformableCSSProperties` can parse + * The CSS Generics of Property Indexed Keyframes {@link PropertyIndexedKeyframes} */ -export type TypeCSSTransformableProperties = { - [K in keyof ICSSComputedTransformableProperties]?: ICSSComputedTransformableProperties[K] | TypeCallback +export type TypeCSSGenericPropertyKeyframes = TypeCommonGenerics | TypeCommonGenerics[]; + +/** + * Support CSS Property Functions {@link TypeComputableAnimationFunction} and normal Common Property Values {@link TypeCommonGenerics} +*/ +export type TypeComputableCSSGenerics = TypeCSSGenericPropertyKeyframes | TypeComputableAnimationFunction; + +/** + * Contains the individual transform properties, `translate, rotate, scale, skew, perspective`, and all their varients + */ +export interface IIndividualTransformProperties { + perspective?: TypeCSSGenericPropertyKeyframes, + + rotate?: TypeCSSGenericPropertyKeyframes | Array, + rotate3d?: TypeCSSGenericPropertyKeyframes | Array, + rotateX?: TypeCSSGenericPropertyKeyframes, + rotateY?: TypeCSSGenericPropertyKeyframes, + rotateZ?: TypeCSSGenericPropertyKeyframes, + + translate?: TypeCSSGenericPropertyKeyframes | Array, + translate3d?: TypeCSSGenericPropertyKeyframes | Array, + translateX?: TypeCSSGenericPropertyKeyframes, + translateY?: TypeCSSGenericPropertyKeyframes, + translateZ?: TypeCSSGenericPropertyKeyframes, + + scale?: TypeCSSGenericPropertyKeyframes | Array, + scale3d?: TypeCSSGenericPropertyKeyframes | Array, + + scaleX?: TypeCSSGenericPropertyKeyframes, + scaleY?: TypeCSSGenericPropertyKeyframes, + scaleZ?: TypeCSSGenericPropertyKeyframes, + + skew?: TypeCSSGenericPropertyKeyframes | Array, + + skewX?: TypeCSSGenericPropertyKeyframes, + skewY?: TypeCSSGenericPropertyKeyframes, + + // matrix?: TypeCSSGenericPropertyKeyframes | Array, + // matrix3d?: TypeCSSGenericPropertyKeyframes | Array, } +/** + * The union of all CSS Property types, ranging from hypenated to cammelCase, including individual transform properties + * + * e.g. + * ```ts + * { + * // ... + * "background-color": "red", + * borderColor: "green" + * } + * ``` + * + * The Full list of CSS & SVG Animatable Properties & Animation Options that are supported excluding the `d` property + * + * Supported Animatable Properties: + * - [Animatable CSS Properties](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties) + * - [SVG Presentation Attributes](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/Presentation) excluding the `d` property + * +*/ +export type TypeCSSProperties = + Properties & + PropertiesHyphen & + PropertiesFallback & + PropertiesHyphenFallback & + + IIndividualTransformProperties & + KebabCasedProperties; + /** - * CSS Properties that are missing from the type definition + * Full list of supported CSS, SVG & Individual Transform Animatable Properties that are supported. + * Also adds support for CSS variables, and the `d` property + * + * Supported Animatable Properties: + * - [Animatable CSS Properties](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties) + * - [SVG Presentation Attributes](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/Presentation) */ -export type TypeMissingCSSProperties = { +export interface IAllSupportedCSSProperties extends TypeCSSProperties { /** * Morphing SVG paths via the `d` property isn't well supported yet, as Gecko (Firefox) & Webkit (Safari) based browsers don't support it yet, and there are other limitations to what the Web Animation API will allow 😭, these limitation are covered in detail by an article published by Adobe about [the current state of SVG animation on the web](https://blog.adobe.com/en/publish/2015/06/05/the-state-of-svg-animation.html#gs.pihpjw). However, animation using paths is now viable through [Motion Path](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Motion_Path). * @@ -58,79 +155,128 @@ export type TypeMissingCSSProperties = { * ] * }) * ``` + * + * Or for more browser support you can use [polymorph-js](https://npmjs.com/polymorph-js) together with {@link AnimateAttributes | tweenAttr} to interpolate between multiple paths: + * + * ```ts + * import { AnimateAttributes } from "@okikio/animate"; + * import { interpolate } from "polymorph-js"; + * + * let startPath = "M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"; + * let endPath = "M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"; + * + * // This is an svg path interpolate function + * // If used in tandem with `AnimateAttributes`, you can create morphing animations + * let morph = interpolate([startPath, endPath], { + * addPoints: 0, + * origin: { x: 0, y: 0 }, + * optimize: "fill", + * precision: 3 + * }); + * + * // `tweenAttr` supports all Animation Options with some restrictions and things to note. + * // 1. Callbacks - the first argument in Animation Options callbacks are set to the progress of the animation beteen 0 and 1, while the other arguments are moved 1 right + * + * // So, animation options look like this + * // `(progress: number, i: number, len: number, el: HTMLElement) => { + * // return progress; + * // } + * + * // 2. Custom easing by default - `easing`, `decimal`, `numPoints`, etc... from `CustomEasing` are supported, meaning you can use any easing function you want, including `spring`, etc... without calling `CustomEasing` on the property you want to apply custom easing to + * // 3. You can use `.updateOptions(...)` to update the animation options of tweens + * + * tweenAttr({ + * target: "svg path", + * d: progress => morph(progress) + * }); + * ``` + * + * Check out the [documentation](https://native.okikio.dev/animate/api/animate-attributes/) to learn more about animating attributes. */ - d?: string | string[] | TypeCallback, - backdropFilter?: string | string[] | TypeCallback, - lineClamp?: number | string | (string | number)[] | TypeCallback, - maskBorder?: string | string[] | TypeCallback, - maskPosition?: number | string | (string | number)[] | TypeCallback, - maskSize?: number | string | (string | number)[] | TypeCallback, - maxLines?: number | string | (string | number)[] | TypeCallback, - offsetPosition?: number | string | (string | number)[] | TypeCallback, - scrollbarColor?: string | string[] | TypeCallback, -} & -/** - * @ignore - */ -{ - [K in TypeAnimatableCSSProperties]?: TypeAnimationOptionTypes -} + d?: Property.OffsetPath | Property.OffsetPath[], -/** - * Full list of CSS & SVG Animatable Properties & Animation Options that are supported - * - * Animatable CSS properties are {@link TypeMissingCSSProperties} - * SVG Presentation Attributes are {@link TypeAnimatableSVGAttributes} - * -*/ -export type TypeCSSAnimationOptions = /** - * @ignore + * `offset`, by default represents the keyframe offset, to ensure the css offset property can still be access, we use `cssOffset` property name. + * The offset CSS shorthand property sets all the properties required for animating an element along a defined path. + * Read more on [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/offset) */ - { - [K in keyof CSSStyleDeclaration]?: CSSStyleDeclaration[K] | CSSStyleDeclaration[K][] | TypeAnimationOptionTypes - } & - /** - * @ignore - */ - { - [K in keyof CSSStyleDeclaration as KebabCase]?: CSSStyleDeclaration[K] | CSSStyleDeclaration[K][] | TypeAnimationOptionTypes - } & - TypeCSSTransformableProperties & - /** - * @ignore - */ - KebabCasedProperties & + cssOffset?: TypeCSSProperties["offset"] | TypeCSSProperties["offset"][], + /** - * @ignore + * Theses are the CSS properties to be animated as Keyframes + * + * Read more on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/setKeyframes) + * + * @remark + * An `object` containing key-value pairs consisting of the property to animate and an `array` of values to iterate over. + * + * @example + * ```ts + * element.animate({ + * opacity: [ 0, 1 ], // [ from, to ] + * color: [ "#fff", "#000" ] // [ from, to ] + * }, 2000); + * ``` + * + * Using this format, the number of elements in each array does not need to be equal. The provided values will be spaced out independently. + + * @example + * ```ts + * element.animate({ + * opacity: [ 0, 1 ], // offset: 0, 1 + * backgroundColor: [ "red", "yellow", "green" ], // offset: 0, 0.5, 1 + * }, 2000); + * ``` + * + * The special keys `offset`, `easing`, and `composite` (described below) may be specified alongside the property values. + + * @example + * ```ts + * element.animate({ + * opacity: [ 0, 0.9, 1 ], + * offset: [ 0, 0.8 ], // Shorthand for [ 0, 0.8, 1 ] + * easing: [ 'ease-in', 'ease-out' ], + * }, 2000); + * ``` + * + * After generating a suitable set of keyframes from the property value lists, each supplied offset is applied to the corresponding keyframe. If there are insufficient values, or if the list contains `null` values, the keyframes without specified offsets will be evenly spaced as with the array format described above. + * + * If there are too few `easing` or `composite` values, the corresponding list will be repeated as needed. + * + * _**Note**: to use `composite` you will need to add it to the {@link AnimationOptions.extend | extend} object as an option_ */ - TypeMissingCSSProperties & - /** - * @ignore - */KebabCasedProperties & - TypeAnimatableSVGAttributes & - /** - * @ignore - */KebabCasedProperties; - + [property: `--${string}`]: TypeComputableCSSGenerics, +} + /** - * Animation options control how an animation is produced, it shouldn't be too different for those who have used `animejs`, or `jquery`'s animate method. - * - * @remark - * An animation option is an object with keys and values that are computed and passed to the `Animate` class to create animations that match the specified options. + * Adds support computable CSS properties to the {@link IAllSupportedCSSProperties} interface */ -export interface IAnimationOptions extends TypeCSSAnimationOptions { - /** - * Determines the DOM elements to animate. You can pass it a CSS selector, DOM elements, or an Array of DOM Elements and/or CSS Selectors. - */ - target?: TypeAnimationTarget, +type TypeComputableCSSProperties = { + [K in keyof IAllSupportedCSSProperties]?: IAllSupportedCSSProperties[K] | TypeComputableAnimationFunction +} - /** - * Alias of `target` - * {@link AnimationOptions.target | target } - */ - targets?: TypeAnimationTarget, +/** + * An Interface that holds the CSS properties from the {@link IAllSupportedCSSProperties} interface as computable callback functions + */ +export interface IComputableCSSProperties extends TypeComputableCSSProperties { } +/** + * Standalone animation configurations (CSS properties aren't included), as in they specify how the animation is played, + * Duration, Delay, Easing, Loop, etc. + * e.g. + * ```ts + * { + * easing: "in-sine", + * duration: 2000, + * delay: 1000, + * endDelay: 1000, + * loop: 2, + * speed: 1.25, + * direction: "alternate", + * } + * ``` + */ +export interface IStandaloneAnimationConfig { /** * Determines the acceleration curve of your animation. Based on the easings of [easings.net](https://easings.net) * @@ -172,7 +318,7 @@ export interface IAnimationOptions extends TypeCSSAnimationOptions { * }); * ``` */ - easing?: KeyframeEffectOptions["easing"] | TypeCallback | string | string[], + easing?: keyof typeof EASINGS | (string & {}) | (keyof typeof EASINGS | (string & {}))[], /** * Determines the duration of your animation in milliseconds. By passing it a callback, you can define a different duration for each element. The callback takes the index of each element, the target dom element, and the total number of target elements as its argument and returns a number. @@ -190,7 +336,7 @@ export interface IAnimationOptions extends TypeCSSAnimationOptions { * }); * ``` */ - duration?: KeyframeEffectOptions["duration"] | number | string | TypeCallback, + duration?: TypeCommonGenerics, /** * Determines the delay of your animation in milliseconds. By passing it a callback, you can define a different delay for each element. The callback takes the index of each element, the target dom element, and the total number of target elements as its argument and returns a number. @@ -208,12 +354,7 @@ export interface IAnimationOptions extends TypeCSSAnimationOptions { * }); * ``` */ - delay?: KeyframeEffectOptions["delay"] | string | number | TypeCallback, - - /** - * Adds an offset ammount to the `delay`, for creating a timeline similar to `animejs` - */ - timelineOffset?: number | string, + delay?: TypeCommonGenerics, /** * Similar to delay but it indicates the number of milliseconds to delay **after** the full animation has played **not before**. @@ -233,15 +374,7 @@ export interface IAnimationOptions extends TypeCSSAnimationOptions { * }); * ``` */ - endDelay?: KeyframeEffectOptions["endDelay"] | string | number | TypeCallback, - - /** - * - * This ensures all `animations` match up to the total duration, and don't finish too early, if animations finish too early when the `.play()` method is called specific animations that are finished will restart while the rest of the animations will continue playing. - * - * _**Note**: you cannot use the `padEndDelay` option and set a value for `endDelay`, the `endDelay` value will replace the padded endDelay_ - */ - padEndDelay?: Boolean, + endDelay?: TypeCommonGenerics, /** * Determines if the animation should repeat, and how many times it should repeat. @@ -259,42 +392,14 @@ export interface IAnimationOptions extends TypeCSSAnimationOptions { * }); * ``` */ - loop?: KeyframeEffectOptions["iterations"] | number | boolean | TypeCallback, - - /** - * Occurs when the animation for one of the targets completes, meaning when animating many targets that finish at different times this will run multiple times. The arguments it takes is slightly different from the rest of the animation options. - * - * The animation argument represents the animation for the current target. - * - * @param element - the current target element - * @param index - the index of the current target element in `Animate.prototype.targets` - * @param total - the total number of target elements - * @param animation - the animation of the current target element - * - * **Warning**: the order of the callback's arguments are in a different order, with the target element first, and the index second. - */ - onfinish?: (element?: HTMLElement, index?: number, total?: number, animation?: Animation) => void, - - /** - * Occurs when the animation for one of the targets is cancelled, meaning when animating many targets that are cancelled at different times this will run multiple times. The arguments it takes is slightly different from the rest of the animation options. - * - * The animation argument represents the animation for the current target. - * - * @param element - the current target element - * @param index - the index of the current target element in `Animate.prototype.targets` - * @param total - the total number of target elements - * @param animation - the animation of the current target element - * - * - * **Warning**: the order of the callback's arguments are in a different order, with the target element first, and the index second. - */ - oncancel?: (element?: HTMLElement, index?: number, total?: number, animation?: Animation) => void, + loop?: TypeCommonGenerics | boolean, /** + * Determines the animation playback rate. Useful in the authoring process to speed up some parts of a long sequence (value above 1) or slow down a specific animation to observe it (value between 0 to 1). * - * Determines if the animation should automatically play immediately after being instantiated. + * _**Note**: negative numbers reverse the animation._ */ - autoplay?: boolean, + speed?: TypeCommonGenerics, /** * Determines the direction of the animation; @@ -304,111 +409,109 @@ export interface IAnimationOptions extends TypeCSSAnimationOptions { * - `normal` but then when the animation reaches the beginning of the animation it alternates going back to the position it started at. */ direction?: KeyframeEffectOptions["direction"] | PlaybackDirection, +} +/** + * Standalone animation options that aren't the standard animation configurations, as in they still specify how the animation is played just in a more abstract manner. + * e.g. + * ```ts + * { + * offset: [0, 0.5], + * direction: "alternate", + * timelineOffset: 200, + * fillMode: "auto", + * keyframes: [ + * { opacity: 1, offset: 0 }, + * { opacity: 0, offset: 0.25 }, + * ], + * composite: "default", + * extend: { + * iterationStart: 0.5 + * } + * } + * ``` + */ +export interface IStandaloneAnimationOptions { /** - * Determines the animation playback rate. Useful in the authoring process to speed up some parts of a long sequence (value above 1) or slow down a specific animation to observe it (value between 0 to 1). + * Allows you to manually set keyframes using a `keyframe` array * - * _**Note**: negative numbers reverse the animation._ - */ - speed?: number | TypeCallback, - - /** - * Defines how an element should look after the animation. + * Read more on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/setKeyframes) * * @remark - * fillMode of: - * - `none` means the animation's effects are only visible while the animation is playing. - * - `forwards` the affected element will continue to be rendered in the state of the final animation frame. - * - `backwards` the animation's effects should be reflected by the element(s) state prior to playing. - * - `both` combining the effects of both forwards and backwards; The animation's effects should be reflected by the element(s) state prior to playing and retained after the animation has completed playing. - * - `auto` if the animation effect fill mode is being applied to is a keyframe effect. "auto" is equivalent to "none". Otherwise, the result is "both". + * An `array` of objects (keyframes) consisting of properties and values to iterate over. This is the canonical format returned by the [getKeyframes()](https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/getKeyframes) method. * - * You can learn more here on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/fill). - - * > _Be careful when using fillMode, it has some problems when it comes to concurrency of animations read more on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/fill). I highly suggest using {@link IAnimationOptions.persist | persist}, as it's less permanent, or better yet use the {@link IAnimationOptions.onfinish | onfinish(...) } method, with {@link Animate.commitStyles | Animate.commitStyles(...)\ } to commit styles._ - */ - fillMode?: KeyframeEffectOptions["fill"] | FillMode, - - /** - * Persists animation state, so, when an animation is complete it keeps said finished animation state. - * Think of it more like a less strict version of {@link IAnimationOptions.fillMode | fillMode}, it was inspired by [motion one](https://motion.dev/). - * - * By default WAAPI resets animations back to their initial state once an animation is complete and fillMode isn't being used. The persist animation option, basically tells Animate to find the final state of all CSS Properties being animated, and then set them, so, once the animation is finished and WAAPI resets animations back to their initial state (so `initial state = final state`) the user doesn't notice difference and it looks like the animation stopped on the final state. - * - * > _**Note**: use this most of the time instead of `fillMode`, as it's impact is less permanent._ - */ - persist?: boolean, - - /** - * Another way to input options for an animation, it's also used to chain animations. + * @example + * ```ts + * element.animate([ + * { // from + * opacity: 0, + * color: "#fff" + * }, + * { // to + * opacity: 1, + * color: "#000" + * } + * ], 2000); + * ``` * - * @remarks - * The `options` animation option is another way to declare options, it can take an instance of `Animate`, a single `Animate` instance in an Array, e.g. `[Animate]` or an object containing animation options. + * Offsets for each keyframe can be specified by providing an `offset` value. + + * @example + * ```ts + * element.animate([ { opacity: 1 }, + * { opacity: 0.1, offset: 0.7 }, + * { opacity: 0 } ], + * 2000); + * ``` * + * _**Note**: `offset` values, if provided, must be between 0.0 and 1.0 (inclusive) and arranged in ascending order._ * - * `options` extends the animation properties of an animation, but more importance is given to the actual animation options object, so, the properties from `options` will be ignored if there is already an animation option with the same name declared. + * It is not necessary to specify an offset for every keyframe. Keyframes without a specified offset will be evenly spaced between adjacent keyframes. * + * --- * - * _**Note**: you can't use this property as a method._ + * The easing to apply between keyframes can be specified by providing an easing `value` as illustrated below. * + * _**Note**: the values for easing in keyframes are limited to "ease", "ease-in", "ease-out", "ease-in-out", "linear", "steps(...)", and "cubic-bezier(...)", to get access to the predefined {@link EASINGS | easings}, you will need to use the function {@link GetEase}._ + * @example * ```ts - * (async () => { - * // animate is Promise-like, as in it has a then() method like a Promise but it isn't a Promise. - * // animate resolves to an Array that contains the Animate instance, e.g. [Animate] - * let [options] = await animate({ - * target: ".div", - * opacity: [0, 1], - * }); + * element.animate([ { opacity: 1, easing: 'ease-out' }, + * { opacity: 0.1, easing: 'ease-in' }, + * { opacity: 0 } ], + * 2000); + * ``` * - * animate({ - * options, + * In this example, the specified easing only applies from the keyframe where it is specified until the next keyframe. Any easing value specified on the options argument, however, applies across a single iteration of the animation — for the entire duration. * - * // opacity overrides the opacity property from `options` - * opacity: [1, 0], - * }); * - * console.log(options); //= Animate - * })(); + * `@okikio/animate` also offers another format called `CSSLikeKeyframe`, + * it basically functions the same way CSS `@keyframe` functions * - * // or - * (async () => { - * let options = await animate({ - * target: ".div", - * opacity: [0, 1], - * duration: 2000, - * - * }); - * - * // Remeber, the `options` animation option can handle Arrays with an Animate instance, e.g. [Animate] - * // Also, remeber that Animate resolves to an Arrays with an Animate instance, e.g. [Animate] - * // Note: the `options` animation option can only handle one Animate instance in an Array and that is alway the first element in the Array - * animate({ - * options, - * opacity: [1, 0], - * }); - * - * console.log(options); //= [Animate] - * })(); - * - * // or - * (async () => { - * let options = { - * target: ".div", - * opacity: [0, 1], - * }; - * - * await animate(options); - * animate({ - * options, - * opacity: [1, 0], - * }); + * @example + * ```ts + * animate({ + * keyframes: { + * "from, 50%, to": { + * opacity: 1 + * }, * - * console.log(options); //= { ... } - * })(); + * "25%, 0.7": { + * opacity: 0 + * } + * } + * }) + * // Results in a keyframe array like this + * //= [ + * //= { opacity: 1, offset: 0 }, + * //= { opacity: 0, offset: 0.25 }, + * //= { opacity: 1, offset: 0.5 }, + * //= { opacity: 0, offset: 0.7 }, + * //= { opacity: 1, offset: 1 } + * //= ] * ``` */ - options?: IAnimationOptions, + keyframes?: (Keyframe & TypeCSSProperties)[], /** * Contols the starting point of certain parts of an animation @@ -433,101 +536,13 @@ export interface IAnimationOptions extends TypeCSSAnimationOptions { * }); * ``` */ - offset?: PropertyIndexedKeyframes["offset"] | (number | string)[] | TypeCallback, - - /** - * Represents the timeline of animation. It exists to pass timeline features to Animations (default is [DocumentTimeline](https://developer.mozilla.org/en-US/docs/Web/API/DocumentTimeline)). - * - * As of right now it doesn't contain any features but in the future when other timelines like the [ScrollTimeline](https://drafts.csswg.org/scroll-animations-1/#scrolltimeline), read the Google Developer article for [examples and demos of ScrollTimeLine](https://developers.google.com/web/updates/2018/10/animation-worklet#hooking_into_the_space-time_continuum_scrolltimeline) - */ - timeline?: AnimationTimeline | null, - - /** - * Allows you to manually set keyframes using a `keyframe` array - * - * Read more on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/setKeyframes) - * - * @remark - * An `array` of objects (keyframes) consisting of properties and values to iterate over. This is the canonical format returned by the [getKeyframes()](https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/getKeyframes) method. - * - * @example - * ```ts - * element.animate([ - * { // from - * opacity: 0, - * color: "#fff" - * }, - * { // to - * opacity: 1, - * color: "#000" - * } - * ], 2000); - * ``` - * - * Offsets for each keyframe can be specified by providing an `offset` value. - - * @example - * ```ts - * element.animate([ { opacity: 1 }, - * { opacity: 0.1, offset: 0.7 }, - * { opacity: 0 } ], - * 2000); - * ``` - * - * _**Note**: `offset` values, if provided, must be between 0.0 and 1.0 (inclusive) and arranged in ascending order._ - * - * It is not necessary to specify an offset for every keyframe. Keyframes without a specified offset will be evenly spaced between adjacent keyframes. - * - * --- - * - * The easing to apply between keyframes can be specified by providing an easing `value` as illustrated below. - * - * _**Note**: the values for easing in keyframes are limited to "ease", "ease-in", "ease-out", "ease-in-out", "linear", "steps(...)", and "cubic-bezier(...)", to get access to the predefined {@link EASINGS | easings}, you will need to use the function {@link GetEase}._ - - * @example - * ```ts - * element.animate([ { opacity: 1, easing: 'ease-out' }, - * { opacity: 0.1, easing: 'ease-in' }, - * { opacity: 0 } ], - * 2000); - * ``` - * - * In this example, the specified easing only applies from the keyframe where it is specified until the next keyframe. Any easing value specified on the options argument, however, applies across a single iteration of the animation — for the entire duration. - * - * - * `@okikio/animate` also offers another format called `CSSLikeKeyframe`, - * it basically functions the same way CSS `@keyframe` functions - * - * @example - * ```ts - * animate({ - * keyframes: { - * "from, 50%, to": { - * opacity: 1 - * }, - * - * "25%, 0.7": { - * opacity: 0 - * } - * } - * }) - * // Results in a keyframe array like this - * //= [ - * //= { opacity: 1, offset: 0 }, - * //= { opacity: 0, offset: 0.25 }, - * //= { opacity: 1, offset: 0.5 }, - * //= { opacity: 0, offset: 0.7 }, - * //= { opacity: 1, offset: 1 } - * //= ] - * ``` - */ - keyframes?: TypeCSSLikeKeyframe | ICSSComputedTransformableProperties[] & Keyframe[] | object[] | TypeCallback, + offset?: (number | string)[], /** * The `composite` property of a `KeyframeEffect` resolves how an element's animation impacts its underlying property values. * * To understand these values, take the example of a `keyframeEffect` value of `blur(2)` working on an underlying property value of `blur(3)`. - * - `replace` - The keyframeEffect overrides the underlying value it is combined with: `blur(2)` replaces `blur(3)`. + * - `replace` (default) - The keyframeEffect overrides the underlying value it is combined with: `blur(2)` replaces `blur(3)`. * - `add` - The keyframeEffect is added to the underlying value with which it is combined (aka additive): `blur(2) blur(3)`. * - `accumulate` - The keyframeEffect is accumulated on to the underlying value: `blur(5)`. * @@ -535,7 +550,29 @@ export interface IAnimationOptions extends TypeCSSAnimationOptions { * * I recommend reading [web.dev](https://web.dev)'s article on [web-animations](https://web.dev/web-animations/#smoother-animations-with-composite-modes). */ - composite?: KeyframeEffectOptions["composite"] | TypeCallback, + composite?: KeyframeEffectOptions["composite"], + + /** + * Adds an offset ammount to the `delay`, for creating a timeline similar to `animejs` + */ + timelineOffset?: number | string, + + /** + * Defines how an element should look after the animation. + * + * @remark + * fillMode of: + * - `none` means the animation's effects are only visible while the animation is playing. + * - `forwards` the affected element will continue to be rendered in the state of the final animation frame. + * - `backwards` the animation's effects should be reflected by the element(s) state prior to playing. + * - `both` combining the effects of both forwards and backwards; The animation's effects should be reflected by the element(s) state prior to playing and retained after the animation has completed playing. + * - `auto` if the animation effect fill mode is being applied to is a keyframe effect. "auto" is equivalent to "none". Otherwise, the result is "both". + * + * You can learn more here on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/fill). + + * > _Be careful when using fillMode, it has some problems when it comes to concurrency of animations read more on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/fill). I highly suggest using {@link IAnimateInstanceConfig.persist | persist}, as it's less permanent, or better yet use the {@link IAnimateInstanceConfig.onfinish | onfinish(...) } method, with {@link Animate.commitStyles | Animate.commitStyles(...)\ } to commit styles._ + */ + fillMode?: KeyframeEffectOptions["fill"] | FillMode, /** * The properties of the `extend` animation option are not interperted or computed, they are given directly to the `Web Animation API`, as way to access features that haven't been implemented in `@okikio/animate`, for example, `iterationStart`. @@ -559,88 +596,226 @@ export interface IAnimationOptions extends TypeCSSAnimationOptions { * }); * ``` */ - extend?: KeyframeEffectOptions | TypeCallback, + extend?: KeyframeEffectOptions +} + +/** + * Stores the final value of computed animation options + * e.g. + * ```ts + * { + * easing: "in-sine", + * duration: 2000, + * delay: 1000, + * endDelay: 1000, + * loop: 2, + * speed: 1.25, + * direction: "alternate", + * offset: [0, 0.5], + * direction: "alternate", + * timelineOffset: 200, + * fillMode: "auto", + * keyframes: [ + * { opacity: 1, offset: 0 }, + * { opacity: 0, offset: 0.25 }, + * ], + * composite: "default", + * extend: { + * iterationStart: 0.5 + * } + * } + * ``` + */ +export interface IStandaloneComputedAnimateOptions extends IStandaloneAnimationConfig, IStandaloneAnimationOptions {} + +/** + * Stores all the info needed to create a the total duration of an animation + */ +export interface ITotalDurationInfo extends IStandaloneComputedAnimateOptions, Omit { + /** + * The total duration of an animation + */ + totalDuration?: number +} + +/** + * Merge both standalone `configs` and `options` into a single type, whose properties are computable. + */ +type TypeComputableAnimationConfig = { + [key in keyof IStandaloneAnimationConfig]?: + IStandaloneAnimationConfig[key] | + TypeComputableAnimationFunction +} & { + [key in keyof IStandaloneAnimationOptions]?: + IStandaloneAnimationOptions[key] | + TypeComputableAnimationFunction + }; + +/** + * Merge both standalone {@link IStandaloneAnimationConfig `configs`} and {@link IStandaloneAnimationOptions `options`} into a single interface, whose properties are computable. + */ +export interface IComputableAnimationConfig extends TypeComputableAnimationConfig { } + +/** + * An interface for Animation options & configs that aren't computable. + */ +export interface INoneComputableAnimationConfig { + /** + * Determines the DOM elements to animate. You can pass it a CSS selector, DOM elements, or an Array of DOM Elements and/or CSS Selectors. + */ + target?: TypeAnimationTarget, + + /** + * Alias of `{@link IAnimationConfig.target }` + */ + targets?: TypeAnimationTarget, /** - * Theses are the CSS properties to be animated as Keyframes * - * Read more on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/setKeyframes) + * This ensures all `animations` match up to the total duration, and don't finish too early, if animations finish too early when the `.play()` method is called specific animations that are finished will restart while the rest of the animations will continue playing. * - * @remark - * An `object` containing key-value pairs consisting of the property to animate and an `array` of values to iterate over. + * _**Note**: you cannot use the `padEndDelay` option and set a value for `endDelay`, the `endDelay` value will replace the padded endDelay_ + */ + padEndDelay?: Boolean, + + /** + * Occurs when the animation for one of the targets completes, meaning when animating many targets that finish at different times this will run multiple times. The arguments it takes is slightly different from the rest of the animation options. * - * @example - * ```ts - * element.animate({ - * opacity: [ 0, 1 ], // [ from, to ] - * color: [ "#fff", "#000" ] // [ from, to ] - * }, 2000); - * ``` + * The animation argument represents the animation for the current target. * - * Using this format, the number of elements in each array does not need to be equal. The provided values will be spaced out independently. + * @param element - the current target element + * @param index - the index of the current target element in `Animate.prototype.targets` + * @param total - the total number of target elements + * @param animation - the animation of the current target element + * + * **Warning**: the order of the callback's arguments are in a different order, with the target element first, and the index second. + */ + onfinish?: (element?: HTMLElement, index?: number, total?: number, animation?: Animation) => void, - * @example - * ```ts - * element.animate({ - * opacity: [ 0, 1 ], // offset: 0, 1 - * backgroundColor: [ "red", "yellow", "green" ], // offset: 0, 0.5, 1 - * }, 2000); - * ``` + /** + * Occurs when the animation for one of the targets is cancelled, meaning when animating many targets that are cancelled at different times this will run multiple times. The arguments it takes is slightly different from the rest of the animation options. * - * The special keys `offset`, `easing`, and `composite` (described below) may be specified alongside the property values. + * The animation argument represents the animation for the current target. + * + * @param element - the current target element + * @param index - the index of the current target element in `Animate.prototype.targets` + * @param total - the total number of target elements + * @param animation - the animation of the current target element + * + * + * **Warning**: the order of the callback's arguments are in a different order, with the target element first, and the index second. + */ + oncancel?: (element?: HTMLElement, index?: number, total?: number, animation?: Animation) => void, + /** + * + * Determines if the animation should automatically play immediately after being instantiated. + */ + autoplay?: boolean, + + /** + * Persists animation state, so, when an animation is complete it keeps said finished animation state. + * Think of it more like a less strict version of {@link IAnimateInstanceConfig.fillMode | fillMode}, it was inspired by [motion one](https://motion.dev/). + * + * By default WAAPI resets animations back to their initial state once an animation is complete and fillMode isn't being used. The persist animation option, basically tells Animate to find the final state of all CSS Properties being animated, and then set them, so, once the animation is finished and WAAPI resets animations back to their initial state (so `initial state = final state`) the user doesn't notice difference and it looks like the animation stopped on the final state. + * + * > _**Note**: use this most of the time instead of `fillMode`, as it's impact is less permanent._ + */ + persist?: boolean, + + /** + * Another way to input options for an animation, it's also used to chain animations. + * + * @remarks + * The `options` animation option is another way to declare options, it can take an instance of `Animate`, a single `Animate` instance in an Array, e.g. `[Animate]` or an object containing animation options. + * + * + * `options` extends the animation properties of an animation, but more importance is given to the actual animation options object, so, the properties from `options` will be ignored if there is already an animation option with the same name declared. + * + * + * _**Note**: you can't use this property as a method._ + * * @example * ```ts - * element.animate({ - * opacity: [ 0, 0.9, 1 ], - * offset: [ 0, 0.8 ], // Shorthand for [ 0, 0.8, 1 ] - * easing: [ 'ease-in', 'ease-out' ], - * }, 2000); - * ``` + * (async () => { + * // animate is Promise-like, as in it has a then() method like a Promise but it isn't a Promise. + * // animate resolves to an Array that contains the Animate instance, e.g. [Animate] + * let [options] = await animate({ + * target: ".div", + * opacity: [0, 1], + * }); * - * After generating a suitable set of keyframes from the property value lists, each supplied offset is applied to the corresponding keyframe. If there are insufficient values, or if the list contains `null` values, the keyframes without specified offsets will be evenly spaced as with the array format described above. + * animate({ + * options, * - * If there are too few `easing` or `composite` values, the corresponding list will be repeated as needed. + * // opacity overrides the opacity property from `options` + * opacity: [1, 0], + * }); * - * _**Note**: to use `composite` you will need to add it to the {@link AnimationOptions.extend | extend} object as an option_ + * console.log(options); //= Animate + * })(); + * + * // or + * (async () => { + * let options = await animate({ + * target: ".div", + * opacity: [0, 1], + * duration: 2000, + * + * }); + * + * // Remeber, the `options` animation option can handle Arrays with an Animate instance, e.g. [Animate] + * // Also, remeber that Animate resolves to an Arrays with an Animate instance, e.g. [Animate] + * // Note: the `options` animation option can only handle one Animate instance in an Array and that is alway the first element in the Array + * animate({ + * options, + * opacity: [1, 0], + * }); + * + * console.log(options); //= [Animate] + * })(); + * + * // or + * (async () => { + * let options = { + * target: ".div", + * opacity: [0, 1], + * }; + * + * await animate(options); + * animate({ + * options, + * opacity: [1, 0], + * }); + * + * console.log(options); //= { ... } + * })(); + * ``` */ - [property: `--${string}`]: TypeAnimationOptionTypes, -}; + options?: IAnimateInstanceConfig, -export type TypeAnimationEvents = "update" | "play" | "pause" | "begin" | "cancel" | "finish" | "error" | "stop" | "playstate-change"; -export type TypePlayStates = "idle" | "running" | "paused" | "finished"; + /** + * Represents the timeline of animation. It exists to pass timeline features to Animations (default is [DocumentTimeline](https://developer.mozilla.org/en-US/docs/Web/API/DocumentTimeline)). + * + * As of right now it doesn't contain any features but in the future when other timelines like the [ScrollTimeline](https://drafts.csswg.org/scroll-animations-1/#scrolltimeline), read the Google Developer article for [examples and demos of ScrollTimeLine](https://developers.google.com/web/updates/2018/10/animation-worklet#hooking_into_the_space-time_continuum_scrolltimeline) + */ + timeline?: AnimationTimeline | null, +} + +/** + * Animate config control how an animation is produced, it shouldn't be too different for those who have used `animejs`, or `jquery`'s animate method. + * + * @remark + * An animate config is an object with keys and values that are computed and passed to the `Animate` class to create animations that match the specified options. + */ +export interface IAnimationConfig extends IComputableAnimationConfig, INoneComputableAnimationConfig { } /** - * CSS properties + * A type that extends both {@link IAnimationConfig} and {@link IComputableCSSProperties}, allowing for both Animate config and CSS properties to be used in the same object */ -export interface ICSSProperties { - [key: string]: TypeSingleValueCSSProperty | Array -}; +type MergedType = Omit & IAnimationConfig; /** - * After being computed as an animation option + * Extends both {@link IAnimationConfig} and {@link IComputableCSSProperties}, allowing for both Animate config and CSS properties to be used in the same object, however, it gives priority to the Animate config even if there are CSS properties with the same name. There are very few cases where this is needed, but it's a good behaviour to have. */ -export interface ICSSComputedTransformableProperties { - perspective?: TypeSingleValueCSSProperty, - rotate?: TypeSingleValueCSSProperty | Array, - rotate3d?: TypeSingleValueCSSProperty | Array, - rotateX?: TypeSingleValueCSSProperty, - rotateY?: TypeSingleValueCSSProperty, - rotateZ?: TypeSingleValueCSSProperty, - translate?: TypeSingleValueCSSProperty | Array, - translate3d?: TypeSingleValueCSSProperty | Array, - translateX?: TypeSingleValueCSSProperty, - translateY?: TypeSingleValueCSSProperty, - translateZ?: TypeSingleValueCSSProperty, - scale?: TypeSingleValueCSSProperty | Array, - scale3d?: TypeSingleValueCSSProperty | Array, - scaleX?: TypeSingleValueCSSProperty, - scaleY?: TypeSingleValueCSSProperty, - scaleZ?: TypeSingleValueCSSProperty, - skew?: TypeSingleValueCSSProperty | Array, - skewX?: TypeSingleValueCSSProperty, - skewY?: TypeSingleValueCSSProperty, - - // matrix?: TypeSingleValueCSSProperty | Array, - // matrix3d?: TypeSingleValueCSSProperty | Array, -} +export interface IAnimateInstanceConfig extends MergedType { } diff --git a/packages/animate/src/unit-conversion.ts b/packages/animate/src/unit-conversion.ts index 04547a1..34e85d2 100644 --- a/packages/animate/src/unit-conversion.ts +++ b/packages/animate/src/unit-conversion.ts @@ -1,7 +1,10 @@ import { Manager } from "@okikio/manager"; -import { getUnit, isValid, toArr } from "./utils"; +import { getUnit, isValid, toArr, isEmpty } from "./utils"; +import { getCSS, getDocument } from "./browser-objects"; +import rgba from "./color-rgba"; + +import type { TypeCSSGenericPropertyKeyframes, TypeCommonGenerics } from "./types"; -import type { TypeSingleValueCSSProperty, ICSSComputedTransformableProperties, ICSSProperties } from "./types"; /** * Returns a closure Function, which adds a unit to numbers but simply returns strings with no edits assuming the value has a unit if it's a string * @@ -26,14 +29,15 @@ export const UnitDEG = addCSSUnit("deg"); /** * Returns a closure function, which adds units to numbers, strings or arrays of both * - * @param unit - a unit function to use to add units to {@link TypeSingleValueCSSProperty | TypeSingleValueCSSProperty's } + * @param unit - a unit function to use to add units to {@link TypeCSSGenericPropertyKeyframes TypeCSSGenericPropertyKeyframes's } * @returns * if input is a string split it into an array at the comma's, and add units * else if the input is a number add the default units * otherwise if the input is an array of both add units according to {@link addCSSUnit} */ + export const CSSValue = (unit: typeof UnitLess) => { - return (input: TypeSingleValueCSSProperty) => { + return (input: TypeCSSGenericPropertyKeyframes): ReturnType[] => { return isValid(input) ? toArr(input).map(val => { if (typeof val != "number" && typeof val != "string") return val; @@ -48,10 +52,10 @@ export const CSSValue = (unit: typeof UnitLess) => { } /** - * Takes `TypeSingleValueCSSProperty` or an array of `TypeSingleValueCSSProperty` and adds units approriately + * Takes `TypeCSSGenericPropertyKeyframes` or an array of `TypeCSSGenericPropertyKeyframes` and adds units approriately * * @param arr - array of numbers, strings and/or an array of array of both e.g. ```[[25, "50px", "60%"], "25 35 60%", 50]``` - * @param unit - a unit function to use to add units to {@link TypeSingleValueCSSProperty | TypeSingleValueCSSProperty's } + * @param unit - a unit function to use to add units to {@link TypeCSSGenericPropertyKeyframes | TypeCSSGenericPropertyKeyframes's } * @returns * an array of an array of strings with units * e.g. @@ -71,11 +75,11 @@ export const CSSValue = (unit: typeof UnitLess) => { * //= ] * ``` */ -export const CSSArrValue = (arr: TypeSingleValueCSSProperty | TypeSingleValueCSSProperty[], unit: typeof UnitLess) => { +export const CSSArrValue = (arr: TypeCSSGenericPropertyKeyframes | TypeCSSGenericPropertyKeyframes[], unit: typeof UnitLess) => { // This is for the full varients of the transform function as well as the 3d varients // zipping the `CSSValue` means if a user enters a string, it will treat each value (seperated by a comma) in that // string as a seperate transition state - return toArr(arr).map(CSSValue(unit)) as TypeSingleValueCSSProperty[]; + return toArr(arr).map(CSSValue(unit)) as TypeCSSGenericPropertyKeyframes[]; } /** Parses CSSValues without adding any units */ @@ -96,21 +100,29 @@ export const CSS_CACHE = new Manager(); * Convert colors to an [r, g, b, a] Array */ export const toRGBAArr = (color = "transparent") => { + let result: number[]; + color = color.trim(); if (CSS_CACHE.has(color)) return CSS_CACHE.get(color); - if (!CSS.supports("background-color", color)) return color; - - let el = document.createElement("div"); - el.style.backgroundColor = color; - - let parent = document.body; - parent.appendChild(el); - - let { backgroundColor } = getComputedStyle(el); - el.remove(); - - let computedColor = /\(([^)]+)\)?/.exec(backgroundColor)?.[1].split(","); - let result = (computedColor.length == 3 ? [...computedColor, "1"] : computedColor).map(v => parseFloat(v)); + if (isEmpty(getCSS())) { + result = rgba(color); + } + + if (!isEmpty(getDocument())) { + if (!getCSS()?.supports("background-color", color)) return color; + + let el = getDocument()?.createElement("div"); + el.style.backgroundColor = color; + + let parent = getDocument()?.body; + parent.appendChild(el); + + let { backgroundColor } = globalThis?.getComputedStyle?.(el); + el.remove(); + + let computedColor = /\(([^)]+)\)?/.exec(backgroundColor)?.[1].split(","); + result = (computedColor.length == 3 ? [...computedColor, "1"] : computedColor).map(v => parseFloat(v)); + } CSS_CACHE.set(color, result); return result; @@ -124,14 +136,14 @@ export const toRGBAArr = (color = "transparent") => { // if (CSS_CACHE.has(value)) return CSS_CACHE.get(value); // if (!CSS.supports("width", value)) return toPX; -// let el = document.createElement(target?.tagName ?? "div"); +// let el = getDocument()?.createElement?.(target?.tagName ?? "div"); // el.style.width = value; -// let parent = target?.parentElement ?? document.body; -// parent.appendChild(el); +// let parent = target?.parentElement ?? getDocument()?.body; +// parent?.appendChild(el); -// let { width: result } = getComputedStyle(el); -// parent.removeChild(el); +// let { width: result } = globalThis?.getComputedStyle?.(el); +// parent?.removeChild(el); // CSS_CACHE.set(value, result); // return result; diff --git a/packages/animate/src/utils.ts b/packages/animate/src/utils.ts index 750e6f6..05e158c 100644 --- a/packages/animate/src/utils.ts +++ b/packages/animate/src/utils.ts @@ -2,20 +2,29 @@ export const flatten = (arr: any[]) => [].concat(...arr); /** Determines whether value is an pure object (not array, not function, etc...) */ -export const isObject = (obj: any) => typeof obj == "object" && !Array.isArray(obj) && typeof obj != "function"; +export const isObject = (obj: any) => + typeof obj == "object" && !Array.isArray(obj) && typeof obj != "function"; /** Determines if an object is empty */ export const isEmpty = (obj: any) => { - for (let _ in obj) { return false; } + for (let _ in obj) { + return false; + } + return true; -} +}; /** * Acts like array.map(...) but for functions */ -export const mapObject = (obj: object, fn: (value: any, key: any, obj: any) => any) => { +export const mapObject = ( + obj: object, + fn: (value: any, key: any, obj: any) => any +) => { let keys = Object.keys(obj); - let key: any, value: any, result = {}; + let key: any, + value: any, + result = {}; for (let i = 0, len = keys.length; i < len; i++) { key = keys[i]; value = obj[key]; @@ -29,12 +38,12 @@ export const mapObject = (obj: object, fn: (value: any, key: any, obj: any) => a export const toStr = (input: any) => `` + input; /** - * Returns the unit of a string, it does this by removing the number in the string + * Returns the unit of a string, it does this by removing the number in the string */ export const getUnit = (str: string | number) => { let num = parseFloat(str as string); return toStr(str).replace(toStr(num), ""); -} +}; /** Convert value to string, then trim any extra white space and line terminator characters from the string. @@ -54,7 +63,7 @@ export const toArr = (input: any): any[] => { } return [input]; -} +}; /** * Checks if a value is valid/truthy; it counts empty arrays and strings as falsey, @@ -69,22 +78,24 @@ export const isValid = (value: any) => { if (Array.isArray(value) || typeof value == "string") return Boolean(value.length); return value != null && value != undefined && !Number.isNaN(value); -} +}; /** Convert a camelCase string to a dash-separated string (opposite of {@link camelCase}) */ export const convertToDash = (str: string) => { - str = str.replace(/([A-Z])/g, letter => `-${letter.toLowerCase()}`); + str = str.replace(/([A-Z])/g, (letter) => `-${letter.toLowerCase()}`); // Remove first dash - return (str.charAt(0) == '-') ? str.substr(1) : str; -} + return str.charAt(0) == "-" ? str.substr(1) : str; +}; /** Convert a dash-separated string into camelCase strings (opposite of {@link convertToDash}) */ export const camelCase = (str: string) => { if (str.includes("--")) return str; - let result = `${str}`.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()); + let result = `${str}`.replace(/-([a-z])/g, (_, letter) => + letter.toUpperCase() + ); return result; -} +}; /** * Return a copy of the object without the keys specified in the keys argument @@ -102,7 +113,7 @@ export const omit = (keys: string[], obj: { [key: string]: any }) => { rest = remaining; } return rest; -} +}; /** * Return a copy of the object with only the keys specified in the keys argument @@ -117,12 +128,11 @@ export const pick = (keys: string[], obj: { [key: string]: any }) => { let rest = {}; for (let key of arr) { - if (isValid(obj[key])) - rest[key] = obj[key]; + if (isValid(obj[key])) rest[key] = obj[key]; } return rest; -} +}; /** * Flips the rows and columns of 2-dimensional arrays @@ -146,10 +156,10 @@ export const pick = (keys: string[], obj: { [key: string]: any }) => { * @returns * returns the new array of grouped elements */ -// (TypeSingleValueCSSProperty | TypeSingleValueCSSProperty[])[] +// (TypeCSSGenericPropertyKeyframes | TypeCSSGenericPropertyKeyframes[])[] export const transpose = (...args: (any | any[])[]) => { let largestArrLen = 0; - args = args.map(arr => { + args = args.map((arr) => { // Convert all values in arrays to an array // This ensures that `arrays` is an array of arrays let result = toArr(arr); @@ -168,10 +178,9 @@ export const transpose = (...args: (any | any[])[]) => { for (let row = 0; row < len; row++) { let val = args[row][col]; - if (isValid(val)) - result[col][row] = val; + if (isValid(val)) result[col][row] = val; } } return result; -} \ No newline at end of file +}; -- knotmirror 0.0.1