UNPKG

motion

Version:

The Motion library for the web

72 lines (69 loc) 2.44 kB
import { addUniqueItem } from '../../../utils/array.es.js'; import { noopReturn } from '../../../utils/noop.es.js'; import { getAnimationData } from '../data.es.js'; /** * A list of all transformable axes. We'll use this list to generated a version * of each axes for each transform. */ const axes = ["", "X", "Y", "Z"]; /** * An ordered array of each transformable value. By default, transform values * will be sorted to this order. */ const order = ["translate", "scale", "rotate", "skew"]; const transformAlias = { x: "translateX", y: "translateY", z: "translateZ", }; const rotation = { syntax: "<angle>", initialValue: "0deg", toDefaultUnit: (v) => v + "deg", }; const baseTransformProperties = { translate: { syntax: "<length-percentage>", initialValue: "0px", toDefaultUnit: (v) => v + "px", }, rotate: rotation, scale: { syntax: "<number>", initialValue: 1, toDefaultUnit: noopReturn, }, skew: rotation, }; const transformPropertyDefinitions = new Map(); const asTransformCssVar = (name) => `--motion-${name}`; /** * Generate a list of every possible transform key */ const transforms = ["x", "y", "z"]; order.forEach((name) => { axes.forEach((axis) => { transforms.push(name + axis); transformPropertyDefinitions.set(asTransformCssVar(name + axis), baseTransformProperties[name]); }); }); /** * A function to use with Array.sort to sort transform keys by their default order. */ const compareTransformOrder = (a, b) => transforms.indexOf(a) - transforms.indexOf(b); /** * Provide a quick way to check if a string is the name of a transform */ const transformLookup = new Set(transforms); const isTransform = (name) => transformLookup.has(name); const addTransformToElement = (element, name) => { const { activeTransforms } = getAnimationData(element); addUniqueItem(activeTransforms, name); element.style.transform = buildTransformTemplate(activeTransforms); }; const buildTransformTemplate = (activeTransforms) => activeTransforms .sort(compareTransformOrder) .reduce(transformListToString, "") .trim(); const transformListToString = (template, name) => `${template} ${name}(var(${asTransformCssVar(name)}))`; export { addTransformToElement, asTransformCssVar, axes, buildTransformTemplate, compareTransformOrder, isTransform, transformAlias, transformPropertyDefinitions };