Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 | 94x 94x 94x 94x 94x 58x 58x 58x 58x 58x 58x 62x 62x 58x 124x 124x 124x 58x 4x 4x 4x 58x 58x 81x 4x 81x 100x 81x 58x 4x 4x 4x 13x 3x 3x 13x 4x 4x 4x 10x 10x 4x 4x 10x 4x 58x 58x 8x 58x 58x 99x 58x 7x 5x 5x 7x 58x 14x 28x 28x 28x 14x 58x 16x 30x 30x 30x 30x 16x 58x 11x 13x 13x 13x 11x 58x 14x 24x 24x 24x 24x 14x 94x 94x 94x 94x 94x 94x 94x 94x 72x 72x 94x 10x 10x 10x 2x 2x 1x 1x 3x 3x 2x 2x 2x 2x 186x 186x 94x 149x 338x | /** * @module Effects/Transform * * @since v1.3.0 */ import * as MC from "@lisn/globals/minification-constants"; import * as MH from "@lisn/globals/minification-helpers"; import { AtLeastOne, Axis, Origin } from "@lisn/globals/types"; import { isValidNum, sum } from "@lisn/utils/math"; import { newXWeakMap } from "@lisn/modules/x-map"; import { EffectInterface, EffectHandler, ScrollOffsets, } from "@lisn/effects/effect"; export type TransformLike = Transform | DOMMatrix | Float32Array; /** * {@link Transform} controls an element's transform as a 3D matrix. */ export class Transform implements EffectInterface<"transform"> { readonly type = "transform"; /** * Returns true if the transform is absolute. If true, its handlers receive * absolute offsets instead of delta values and applying the transform * discards all previous ones, including their {@link perspective}. */ readonly isAbsolute: () => boolean; /** * Applies all transforms for the given scroll offsets. * * @throws {@link Errors.LisnUsageError | LisnUsageError} * If any of the values returned by the {@link EffectHandler} * s is invalid. * * @returns The same {@link Transform} instance. */ readonly apply: (offsets: ScrollOffsets) => Transform; /** * Returns a **new** live transform that has all the handlers from this one * and the given transforms, in order. The resulting effective state (matrix) * is the combined product of its current matrix and that of all the other * given ones. * * **NOTE:** If any of the given transforms is * {@link TransformConfig.isAbsolute | absolute}, all previous ones are * essentially discarded and the resulting transform becomes absolute. * * @returns **A new** {@link Transform} instance. */ readonly toComposition: (...others: Transform[]) => Transform; /** * Returns an object with the `transform` property and value equal to what's * returned by {@link toString}. * * @param relativeTo See {@link toMatrix} */ readonly toCss: (relativeTo?: TransformLike) => Record<string, string>; /** * Returns a `perspective(...) matrix3d(...)` string for use as a CSS property. * * If no perspective has been set, it's omitted from the string. * * @param relativeTo See {@link toMatrix} */ readonly toString: (relativeTo?: TransformLike) => string; /** * Returns the current effective perspective (since the last call to * {@link apply} set on the transform. If a number was passed, it is converted * to a CSS length string in pixels. * * @returns A non-empty CSS string for perspective or `undefined` */ readonly toPerspective: () => string | undefined; /** * Returns a {@link https://developer.mozilla.org/en-US/docs/Web/API/DOMMatrixReadOnly | DOMMatrixReadOnly} representing the transform. * * @param relativeTo If given, then this matrix is first inverted and used as * a pre-multiplication */ readonly toMatrix: (relativeTo?: TransformLike) => DOMMatrixReadOnly; /** * Returns a {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array | Float32Array} representing the transform. * * @param relativeTo See {@link toMatrix} */ readonly toFloat32Array: (relativeTo?: TransformLike) => Float32Array; /** * Sets the transform's perspective. Perspective applies at the start of * transforms and subsequent calls to this method always override previous * ones, i.e. it is not additive. * * @returns The same {@link Transform} instance. */ readonly perspective: ( handler: EffectHandler<PerspectiveHandlerReturn>, ) => Transform; /** * Translates the transform. * * @returns The same {@link Transform} instance. */ readonly translate: ( handler: EffectHandler<TranslateHandlerReturn>, ) => Transform; /** * Scales the transform. * * @returns The same {@link Transform} instance. */ readonly scale: (handler: EffectHandler<ScaleHandlerReturn>) => Transform; /** * Skews the transform. * * **NOTE:** If skewing along both axis (i.e. both `degX` and `degY` given, * or `deg` is given), then skewing is done first along X, then along Y. * * @returns The same {@link Transform} instance. */ readonly skew: (handler: EffectHandler<SkewHandlerReturn>) => Transform; /** * Rotates the transform around the given axis. * * @returns The same {@link Transform} instance. */ readonly rotate: (handler: EffectHandler<RotateHandlerReturn>) => Transform; constructor(config?: TransformConfig) { const { isAbsolute = false, init } = config ?? {}; const selfM = newMatrix(false, init); const processedHandlers: EffectHandler<void>[] = []; let perspective: string | undefined = undefined; const addOwnHandler = <T extends HandlerTuple>( original: T, processed: EffectHandler<void>, ) => { processedHandlers.push(processed); saveHandlerFor(this, original); }; const toMatrix = (relativeTo?: TransformLike) => { const m = newMatrix(true, selfM); const relM = relativeTo ? newMatrix(true, relativeTo) : null; return relM ? relM.inverse().multiply(m) : m; }; const reset = () => { selfM.m12 = selfM.m13 = selfM.m14 = selfM.m21 = selfM.m23 = selfM.m24 = selfM.m31 = selfM.m32 = selfM.m34 = selfM.m41 = selfM.m42 = selfM.m43 = 0; selfM.m11 = selfM.m22 = selfM.m33 = selfM.m44 = 1; return this; }; // ---------- this.isAbsolute = () => isAbsolute; this.apply = (offsets) => { if (isAbsolute) { reset(); } for (const handler of processedHandlers) { handler(offsets); } return this; }; this.toComposition = (...others) => { let toCombine: Transform[] = []; let resIsAbsolute = false; // Avoid computing products unnecessarily, so filter first. for (const t of [this, ...others]) { if (t.isAbsolute()) { resIsAbsolute = true; toCombine = []; } toCombine.push(t); } const resultInit = new DOMMatrix(); const resultHandlers: HandlerTuple[] = []; for (const t of toCombine) { resultInit.multiplySelf(t.toMatrix()); resultHandlers.push(...getHandlersFor(t)); } const result = new Transform({ isAbsolute: resIsAbsolute, init: resultInit, }); for (const h of resultHandlers) { addAndSaveHandlerFor(result, h); } return result; }; this.toCss = (relativeTo) => ({ transform: this.toString(relativeTo) }); this.toString = (relativeTo) => (perspective ? `perspective(${perspective}) ` : "") + toMatrix(relativeTo).toString(); this.toPerspective = () => perspective; this.toMatrix = toMatrix; this.toFloat32Array = (relativeTo) => toMatrix(relativeTo).toFloat32Array(); this.perspective = (handler) => { addOwnHandler([PERSPECTIVE, handler], (offsets) => { const res = handler(offsets); perspective = MH.isEmpty(res) ? undefined : MH.isString(res) ? res : `${res}px`; }); return this; }; this.translate = (handler) => { addOwnHandler([TRANSLATE, handler], (offsets) => { const { x = 0, y = 0, z = 0 } = handler(offsets) ?? {}; validateInputs("Translate distance", [x, y, z]); selfM.translateSelf(x, y, z); }); return this; }; this.scale = (handler) => { addOwnHandler([SCALE, handler], (offsets) => { const { s = 1, sx = s, sy = s, sz = s, origin = [0, 0, 0], } = handler(offsets) ?? {}; validateInputs("Scale factor", [sx, sy, sz], true); validateInputs("Origin", origin); selfM.scaleSelf(sx, sy, sz, ...origin); }); return this; }; this.skew = (handler) => { addOwnHandler([SKEW, handler], (offsets) => { const { deg = 0, degX = deg, degY = deg } = handler(offsets) ?? {}; validateInputs("Skew angle", [degX, degY]); selfM.skewXSelf(degX).skewYSelf(degY); }); return this; }; this.rotate = (handler) => { addOwnHandler([ROTATE, handler], (offsets) => { const { deg = 0, axis = [0, 0, 1] } = handler(offsets) ?? {}; validateInputs("Rotation angle", [deg]); validateInputs("Rotation axis", [sum(...axis)], true); selfM.rotateAxisAngleSelf(axis[0], axis[1] ?? 0, axis[2] ?? 0, deg); }); return this; }; } } /** * Should return the perspective as a number (if in pixels) or as a CSS * perspective string. * * Returning an empty string results in clearing the perspective completely. * * @defaultValue undefined */ export type PerspectiveHandlerReturn = number | string; /** * Should return the translation distances along one or more axes. */ export type TranslateHandlerReturn = AtLeastOne<{ /** * The translation distance in pixels along the X-axis. * * @defaultValue 0 */ x: number; /** * The translation distance in pixels along the Y-axis. * * @defaultValue 0 */ y: number; /** * The translation distance in pixels along the Z-axis. * * @defaultValue 0 */ z: number; }>; /** * Should return the scaling factor along one or more axes. */ export type ScaleHandlerReturn = AtLeastOne<{ /** * The default scaling factor for any axis if not overridden by {@link sx}, * {@link sy} or {@link sz}. This would result in all three axes being * scaled. * * @defaultValue 1 */ s: number; /** * The translation distance in pixels along the X-axis. * * @defaultValue {@link s} */ sx: number; /** * The translation distance in pixels along the Y-axis. * * @defaultValue {@link s} */ sy: number; /** * The translation distance in pixels along the Z-axis. * * @defaultValue {@link s} */ sz: number; }> & { /** * The transform origin. * * @defaultValue [0,0,0] */ origin?: Origin; }; /** * Should return the skewing angle along one or more axes. * * **NOTE:** If skewing along both axis (i.e. both `degX` and `degY` given, or * `deg` is given), then skewing is done first along X, then along Y. */ export type SkewHandlerReturn = AtLeastOne<{ /** * The skewing angle in degrees for either axis if not overridden by * {@link degX} or {@link degY}. This would result in both axes being skewed. * * @defaultValue 0 */ deg: number; /** * The skewing angle in degrees along the X-axis. * * @defaultValue {@link deg} */ degX: number; /** * The skewing angle in degrees along the Y-axis. * * @defaultValue {@link deg} */ degY: number; }>; /** * Should return the rotation angle and axis of rotation. */ export type RotateHandlerReturn = { /** * The angle in degrees to rotate. */ deg: number; /** * The axis of rotation. * * @defaultValue [0,0,1] // The Z-axis */ axis?: Axis; }; export type TransformConfig = { /** * If this is true, the {@link EffectHandler}s will receive absolute scroll * offsets in {@link ScrollOffsets} and the current matrix will be reset back * to the identity at each invocation to {@link Transform.apply | apply}. * * Otherwise, the {@link EffectHandler}s will receive delta values for the * scroll offsets and the current matrix will be multiplied by the new * transforms returned by the handlers. * * @defaultValue false */ isAbsolute?: boolean; /** * Initial transform to begin with. Only useful if {@link isAbsolute} is * `true`, otherwise it will be discarded on {@link Transform.apply | apply}. * * @defaultValue undefined // identity matrix */ init?: TransformLike; }; // ---------------------------------------- const PERSPECTIVE: unique symbol = MC.SYMBOL() as typeof PERSPECTIVE; const TRANSLATE: unique symbol = MC.SYMBOL() as typeof TRANSLATE; const SCALE: unique symbol = MC.SYMBOL() as typeof SCALE; const SKEW: unique symbol = MC.SYMBOL() as typeof SKEW; const ROTATE: unique symbol = MC.SYMBOL() as typeof ROTATE; type HandlersMap = { [PERSPECTIVE]: EffectHandler<PerspectiveHandlerReturn>; [TRANSLATE]: EffectHandler<TranslateHandlerReturn>; [SCALE]: EffectHandler<ScaleHandlerReturn>; [SKEW]: EffectHandler<SkewHandlerReturn>; [ROTATE]: EffectHandler<RotateHandlerReturn>; }; type HandlerTuple = { [K in keyof HandlersMap]: [K, HandlersMap[K]]; }[keyof HandlersMap]; const allUserHandlersMap = newXWeakMap<Transform, HandlerTuple[]>(() => []); const getHandlersFor = (t: Transform) => allUserHandlersMap.sGet(t); const saveHandlerFor = <T extends HandlerTuple>( transform: Transform, tuple: T, ) => { const handlers = getHandlersFor(transform); handlers.push(tuple); }; const addAndSaveHandlerFor = <T extends HandlerTuple>( transform: Transform, tuple: T, ) => { saveHandlerFor(transform, tuple); const [type, handler] = tuple; switch (type) { case PERSPECTIVE: transform.perspective(handler); break; case TRANSLATE: transform.translate(handler); break; case SCALE: transform.scale(handler); break; case SKEW: transform.skew(handler); break; case ROTATE: transform.rotate(handler); break; default: throw MH.bugError("Unhandled transform effect category"); } }; function newMatrix(readonly: true, init?: TransformLike): DOMMatrixReadOnly; function newMatrix(readonly: false, init?: TransformLike): DOMMatrix; function newMatrix(readonly: boolean, init?: TransformLike) { const initM = MH.isInstanceOf(init, Transform) ? init.toMatrix() : init; return new (readonly ? DOMMatrixReadOnly : DOMMatrix)( MH.isNullish(initM) ? initM : MH.arrayFrom( MH.isInstanceOf(initM, DOMMatrixReadOnly) ? initM.toFloat32Array() : initM, ), ); } const validateInputs = ( name: string, inputs: number[], requireNonZero = false, ) => { for (const i of inputs) { Iif (!isValidNum(i) || (requireNonZero && MH.abs(i) < 1e-10)) { throw MH.usageError( `${name} must be finite${requireNonZero ? " and non-zero" : ""}`, ); } } }; declare module "@lisn/effects/effect" { interface EffectRegistry { transform: Transform; } } |