Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/okikio/native. An initiative which aims to make it easy to create complex, light-weight, and perfor okikio.github.io/native
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430import { CSSArrValue, UnitPX, UnitPXCSSValue, UnitDEG, UnitLess, UnitDEGCSSValue, UnitLessCSSValue } from "./unit-conversion";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 { TypeCSSGenericPropertyKeyframes, IIndividualTransformProperties, IComputableCSSProperties, IAllSupportedCSSProperties } from "./types";
export interface ITransformFunctions { [key: string]: (value: TypeCSSGenericPropertyKeyframes | Array<TypeCSSGenericPropertyKeyframes>) => TypeCSSGenericPropertyKeyframes | Array<TypeCSSGenericPropertyKeyframes>;}
/** * Details how to compute each transform function */export const TransformFunctions: ITransformFunctions = { "translate": value => CSSArrValue(value, UnitPX), "translate3d": value => CSSArrValue(value, UnitPX), "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: 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: TypeCSSGenericPropertyKeyframes) => UnitLessCSSValue(value), "scaleY": (value: TypeCSSGenericPropertyKeyframes) => UnitLessCSSValue(value), "scaleZ": (value: TypeCSSGenericPropertyKeyframes) => UnitLessCSSValue(value),
"skew": value => CSSArrValue(value, UnitDEG), "skewX": (value: TypeCSSGenericPropertyKeyframes) => UnitDEGCSSValue(value), "skewY": (value: TypeCSSGenericPropertyKeyframes) => UnitDEGCSSValue(value),
"perspective": (value: TypeCSSGenericPropertyKeyframes) => UnitPXCSSValue(value),
// "matrix": value => CSSArrValue(value, UnitLess), // "matrix3d": value => CSSArrValue(value, UnitLess),};
/** * Store all the supported transform functions as an Array */export const TransformFunctionNames = Object.keys(TransformFunctions);
/** * Removes dashes from CSS properties & maps the values to camelCase keys */export const CSSCamelCase = (obj: object) => { let keys = Object.keys(obj); let key: any, value: any, result = {}; for (let i = 0, len = keys.length; i < len; i++) { key = camelCase(keys[i]); value = obj[keys[i]]; result[key] = value; }
return result;}
/** * Creates the transform property text */export const createTransformProperty = (transformFnNames: string[], arr: any[]) => { let result = ""; let len = transformFnNames.length; for (let i = 0; i < len; i++) { let name = transformFnNames[i]; let value = arr[i]; if (isValid(value)) result += `${name}(${Array.isArray(value) ? value.join(", ") : value}) `; }
return result.trim();}
/** Common CSS Property names with the units "px" as an acceptable value */export const CSSPXDataType = ["margin", "padding", "size", "width", "height", "left", "right", "top", "bottom", "radius", "gap", "basis", "inset", "outline-offset", "translate", "perspective", "thickness", "position", "distance", "spacing"].map(camelCase).join("|");
/** * It fills in the gap between different size transform functions, so, for example, * ```ts * { * translateX: [50, 60, 80, 90], * scale: [0.5, 2] * } * ``` * * There are more values of `translateX`, so the `transform` property created will look like this, * ```ts * { * transform: [ * "translateX(50px) scale(0.5)", * "translateX(60px) scale(2)", * "translateX(80px)", * "translateX(90px)" * ] * } * ``` * * `arrFill` interpolates between all missing portions of transform functions, and helps create a uniform size transform property, * e.g. * ```ts * { * transform: [ * "translateX(50px) scale(0.5)", * "translateX(60px) scale(1)", * "translateX(80px) scale(1.5)", * "translateX(90px) scale(2)" * ] * } * ``` */export const arrFill = (arr: any[] | any[][], maxLen?: number) => { // Ensure all transform function Arrays are the same length to create smooth motion maxLen = maxLen ?? Math.max(...arr.map((value: any[]) => value.length)); return arr.map((value: any[]) => { let len = value.length; let is2dArray = value.every(v => Array.isArray(v));
// If value is a one dimensional Array if (!is2dArray) { if (len !== maxLen) { return Array.from(Array(maxLen), (_, i) => { // `interpolateString` requires a minimum of 2 elements in an array to interploate between, // repeat the first value twice if there are not enough values to satisfy `interpolateString` let values = len == 1 ? Array(2).fill(value[0]) : value; return interpolateString(i / (maxLen - 1), values); }); } else return value; }
// * transpose 2d Array (because of what the array row and col's represent, to ensure we are calling arrFill on the proper axes), // * run arrFill to ensure a set size, // * transpose once more to return to it's original form but with all Arrays in the 2d array having the same size else return transpose(...arrFill(transpose(...value), maxLen)); });}
/** * Removes the need for the full transform statement in order to use translate, rotate, scale, skew, or perspective including their X, Y, Z, and 3d varients * Also, adds the ability to use single string or number values for transform functions * * _**Note**: the `transform` animation option will override all transform function properties_ * * _**Note**: the order of where/when you define transform function matters, for example, depending on the order you define `translate`, and `rotate`, you can create change the radius of the rotation_ * * @param properties - the CSS properties to transform * * @example * ```ts * ParseTransformableCSSProperties({ * // It will automatically add the "px" units for you, or you can write a string with the units you want * translate3d: [ * "25 35 60%", * [50, "60px", 70], * ["70", 50] * ], * translate: "25 35 60%", * translateX: [50, "60px", "70"], * translateY: ["50, 60", "60"], // Note: this will actually result in an error, make sure to pay attention to where you are putting commas * translateZ: 0, * perspective: 0, * opacity: "0, 5", * scale: [ * [1, "2"], * ["2", 1] * ], * rotate3d: [ * [1, 2, 5, "3deg"], // The last value in the array must be a string with units for rotate3d * [2, "4", 6, "45turn"], * ["2", "4", "6", "-1rad"] * ], * * // Units are required for non transform CSS properties * // String won't be split into array, they will be wrappeed in an Array * // It will transform border-left to camelCase "borderLeft" * "border-left": 50, * "offset-rotate": "10 20", * margin: 5, * * // When writing in this formation you must specify the units * padding: "5px 6px 7px" * }) * * // On Chromium based browsers, e.g. Chrome, Edge, Brave, Opera, etc... or browsers that support `CSS.registerProperty` this will be the result * //= { * //= "--translate3d0": [ "25px", "50px", "70px" ], * //= "--translate3d1": [ "35px", "60px", "50px" ], * //= "--translate3d2": [ "60%", "70px" ], * //= "--translate0": [ "25px" ], * //= "--translate1": [ "35px" ], * //= "--translateX": [ "50px", "60px", "70px" ], * //= "--translateY": [ "50,,60", "60px" ], * //= "--translateZ": [ "0px" ], * //= "--rotate3d0": [ "1deg", "2deg", "2deg" ], * //= "--rotate3d1": [ "2deg", "4deg", "4deg" ], * //= "--rotate3d2": [ "5deg", "6deg", "6deg" ], * //= "--rotate3d3": [ "3deg", "45turn", "-1rad" ], * //= "--scale0": [ "1", "2" ], * //= "--scale1": [ "2", "1" ], * //= "--perspective": [ "0px" ], * //= "opacity": [ "0, 5" ], * //= "borderLeft": [ "50px" ], * //= "offsetRotate": [ "10deg", "20deg" ], * //= "margin": [ "5px" ], * //= "padding": [ "5px", "6px", "7px" ] * //= } * * // Browsers that don't support `CSS.registerProperty` will result in the following, namely Firefox and Safari * //= { * //= transform: [ * //= // `translateY(50, 60)` will actually result in an error * //= 'translate(25px) translate3d(25px, 35px, 60%) translateX(50px) translateY(50, 60) translateZ(0px) rotate3d(1, 2, 5, 3deg) scale(1, 2) perspective(0px)', * //= 'translate(35px) translate3d(50px, 60px, 70px) translateX(60px) translateY(60px) rotate3d(2, 4, 6, 45turn) scale(2, 1)', * //= 'translate(60%) translate3d(70px, 50px) translateX(70px) rotate3d(2, 4, 6, -1rad)' * //= ], * //= opacity: [ '0', '5' ], * //= borderLeft: ["50px"], * //= * //= // Notice the "deg" * //= offsetRotate: ["10deg", "20deg"], * //= margin: ["5px"], * //= padding: ["5px 6px 7px"] * //= } * * // The key difference between the two is that the former will allow other animations to be used to * // manipulate multiple different transforms at the same time, * // while the latter will not, and must continously update the transform property, * // meaning that new animations will always override the previous ones on the same element, * // on browsers that *don't* support `CSS.registerProperty` * ``` * * @returns * an object with a properly formatted `transform` and `opactity`, as well as other unformatted CSS properties * ``` */export const ParseTransformableCSSProperties = (properties: IComputableCSSProperties, USE_CSS_VARS = false): IComputableCSSProperties => { // Convert dash seperated strings to camelCase strings let AllCSSProperties = CSSCamelCase(properties) as IComputableCSSProperties; let rest: IComputableCSSProperties; let transform: string[];
if (CSSVarSupport && USE_CSS_VARS) { rest = Object.assign({}, omit(transformProperyNames, AllCSSProperties), toCSSVars(AllCSSProperties)); } else { // Adds support for ordered transforms let transformFunctionNames = Object.keys(AllCSSProperties) .filter(key => TransformFunctionNames.includes(key));
let transformFunctionValues = transformFunctionNames .map((key) => TransformFunctions[key](AllCSSProperties[key]));
transformFunctionValues = arrFill(transformFunctionValues);
// Create the transform string transform = transpose(...transformFunctionValues) .filter(isValid) .map(arr => createTransformProperty(transformFunctionNames, arr));
rest = omit(TransformFunctionNames, AllCSSProperties); }
// Wrap non array CSS property values in an array rest = mapObject(rest, (value, key) => { let unit: typeof UnitDEGCSSValue | typeof UnitPXCSSValue;
// If the property key doesn't have the word color in it, try to add the default "px" or "deg" to it if (!/color|shadow/i.test(key)) { let isAngle = /rotate/i.test(key); let isLength = new RegExp(CSSPXDataType, "i").test(key) || (!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 // so, to avoid this bug, I create a new instance every time if (isAngle || isLength) { // If the key has rotate in it's name use "deg" as a default unit if (isAngle) unit = UnitDEGCSSValue;
// If the key is for a common CSS Property name which has the units "px" as an acceptable value // try to add "px" as the default unit else if (isLength) unit = UnitPXCSSValue;
// Note: we first apply units, to make sure if it's a simple number, then units are added // but otherwise, if it's "margin", "padding", "inset", etc.. with values like "55 60 70 5em" // it can easily include the units required return unit(value).map(str => { // To support multi-value CSS properties like "margin", "padding", and "inset" // split the value into an array using spaces as the seperator // then apply the valid default units and join them back with spaces // seperating them
let arr = trim(str).split(/\s+/); return unit(arr).join(" "); }); } }
return [].concat(value).map(toStr); });
return Object.assign({}, isValid(transform) ? { transform } : null, rest);}
/** * Similar to {@link ParseTransformableCSSProperties} except it transforms the CSS properties in each Keyframe * @param keyframes - an array of keyframes with transformable CSS properties * @returns * an array of keyframes, with transformed CSS properties */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 IIndividualTransformProperties & Keyframe; if (CSSVarSupport && USE_CSS_VARS) { return { rest: Object.assign({}, toCSSVars(AllCSSProperties), omit(transformProperyNames, AllCSSProperties)), transformFunctions: null }; }
let { translate, translate3d, translateX, translateY, translateZ, rotate, rotate3d, rotateX, rotateY, rotateZ, scale, scale3d, scaleX, scaleY, scaleZ, skew, skewX, skewY, perspective, // matrix, // matrix3d,
// easing, // iterations, // offset, ...rest } = AllCSSProperties;
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 TypeCSSGenericPropertyKeyframes); rotate3d = UnitLessCSSValue(rotate3d as TypeCSSGenericPropertyKeyframes); rotateX = UnitDEGCSSValue(rotateX)[0]; rotateY = UnitDEGCSSValue(rotateY)[0]; rotateZ = UnitDEGCSSValue(rotateZ)[0];
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 TypeCSSGenericPropertyKeyframes); skewX = UnitDEGCSSValue(skewX)[0]; skewY = UnitDEGCSSValue(skewY)[0];
perspective = UnitPXCSSValue(perspective)[0];
// matrix = UnitLessCSSValue(matrix as TypeCSSGenericPropertyKeyframes); // matrix3d = UnitLessCSSValue(matrix3d as TypeCSSGenericPropertyKeyframes);
return { rest, transformFunctions: [translate3d, translate, translateX, translateY, translateZ, rotate3d, rotate, rotateX, rotateY, rotateZ, scale3d, scale, scaleX, scaleY, scaleZ, skew, skewX, skewY, perspective] //, matrix, matrix3d }; }).map(({ rest, transformFunctions }) => { let transform = CSSVarSupport ? null : createTransformProperty(TransformFunctionNames, transformFunctions); rest = mapObject(rest as object, (value, key) => { let unit: typeof UnitDEGCSSValue | typeof UnitPXCSSValue; value = toStr(value);
// If key doesn't have the word color in it, try to add the default "px" or "deg" to it if (!/color|shadow/i.test(key)) { let isAngle = /rotate/i.test(key); let isLength = new RegExp(CSSPXDataType, "i").test(key);
// 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 // so, to avoid this bug, I create a new instance every time if (isAngle || isLength) { // If the key has rotate in it's name use "deg" as a default unit if (isAngle) unit = UnitDEGCSSValue;
// If the key is for a common CSS Property name which has the units "px" as an acceptable value // try to add "px" as the default unit else if (isLength) unit = UnitPXCSSValue;
// To support multi-value CSS properties like "margin", "padding", and "inset" // with values like "55 60 70 5em", split the value into an array using spaces as the seperator // then apply the valid default units and join them back with spaces // seperating them return unit(value).join(" "); } }
return value; });
return Object.assign({}, isValid(transform) ? { transform } : null, rest); });}