UNPKG

unifiedtransform

Version:

The RAW library to work with CSS transform strings

13 lines (11 loc) 2.67 kB
/* UnifiedTransform v0.4.2 8/16/2025 https://github.com/rawify/UnifiedTransform.js Copyright (c) 2025, Robert Eisele (https://raw.org/) Licensed under the MIT license. */ 'use strict';(function(u){function d(a){return"number"===typeof a?a:parseFloat(a)||0}function f(){this.matrix=[1,0,0,1,0,0]}const q=2*Math.PI/360,r=/(matrix|translate|translateX|translateY|scale|rotate|skewX|skewY)\s*\(([^)]+)\)/g,t=/[\s,]+/;f.prototype={translate:function(a,c){return this.applyMatrix([1,0,0,1,d(String(a).replace("px",""))||0,d(String(c).replace("px",""))||0])},scale:function(a,c=null){null===c&&(c=a);return this.applyMatrix([d(a)||1,0,0,d(c)||1,0,0])},rotate:function(a,c,b){"string"== typeof a?-1!==a.indexOf("rad")?(a=a.replace("rad",""),a=d(a)):(a=a.replace("deg",""),a=d(a)*q):a*=q;let e=Math.cos(a);a=Math.sin(a);void 0!==c&&this.translate(c,b||0);this.applyMatrix([e,a,-a,e,0,0]);return void 0!==c?this.translate(-c,-(b||0)):this},skewX:function(a){a=Math.tan(d(a)*q);return this.applyMatrix([1,0,a,1,0,0])},skewY:function(a){a=Math.tan(d(a)*q);return this.applyMatrix([1,a,0,1,0,0])},applyMatrix:function(a,c="CSS"){let [b,e,h,k,l,v]=this.matrix;let m,n,p;if("CSS"===c){c=d(a[0]); var g=d(a[1]);m=d(a[2]);n=d(a[3]);p=d(a[4]);a=d(a[5])}else"2D"===c?(g=a[0],a=a[1],c=d(g[0]),m=d(g[1]),p=d(g[2]),g=d(a[0]),n=d(a[1]),a=d(a[2])):(c=d(a[0]),m=d(a[1]),p=d(a[2]),g=d(a[3]),n=d(a[4]),a=d(a[5]));this.matrix=[b*c+h*g,e*c+k*g,b*m+h*n,e*m+k*n,b*p+h*a+l,e*p+k*a+v];return this},transform:function(a){r.lastIndex=0;for(let c;null!==(c=r.exec(a));){t.lastIndex=0;const b=c[2].trim().split(t);switch(c[1]){case "matrix":6===b.length&&this.applyMatrix(b);break;case "translate":1===b.length?this.translate(b[0], 0):2===b.length&&this.translate(b[0],b[1]);break;case "translateX":this.translate(b[0],0);break;case "translateY":this.translate(0,b[0]);break;case "scale":1===b.length?this.scale(b[0],b[0]):2===b.length&&this.scale(b[0],b[1]);break;case "rotate":1===b.length?this.rotate(b[0],0,0):3===b.length&&this.rotate(b[0],b[1],b[2]);break;case "skewX":1===b.length&&this.skewX(b[0]);break;case "skewY":1===b.length&&this.skewY(b[0])}}return this},eval:function(a,c){const b=this.matrix;return[a*b[0]+c*b[2]+b[4], a*b[1]+c*b[3]+b[5]]},toMatrix:function(a="flat"){const [c,b,e,h,k,l]=this.matrix;return"CSS"===a?[c,b,e,h,k,l]:"2D"===a?[[c,e,k],[b,h,l],[0,0,1]]:[c,e,k,b,h,l,0,0,1]},toTransformString:function(){return"matrix("+this.matrix.join(", ")+")"}};"function"===typeof define&&define.amd?define([],function(){return f}):"object"===typeof exports?(Object.defineProperty(f,"__esModule",{value:!0}),f["default"]=f,f.UnifiedTransform=f,module.exports=f):u.UnifiedTransform=f})(this);