KeyframeKit

website·Indexed 32 days ago

https://keyframekit.berryscript.com

A JavaScript library designed to provide full playback control over CSS animations. It includes a KeyframesFactory for parsing and managing keyframes, as well as utilities for handling KeyframeEffectParameters and CSS stylesheets.

Tokens
2.6K
Snippets
21
Records
26
Agent score
57%

What's inside KeyframeKit

  1. Overview of KeyframeKit

    KeyframeKit is a lightweight TypeScript library that converts CSS @keyframes animations into Web Animations API-compatible animations. This allows developers to play CSS-defined animations from JavaScript with full playback control (such as pausing, reversing, and tracking progress) while maintaining hardware-accelerated performance.
  2. Define animations in JavaScript using KeyframeEffectParameters

    The KeyframeEffectParameters class allows you to define animations entirely in JavaScript. You can specify offset (0 to 1, equivalent to CSS percentages) and the corresponding property values for each offset.
    import { KeyframeEffectParameters } from 'keyframekit';
    
    const linkTextHoverAnim = new KeyframeEffectParameters({
      keyframes: {
        // 0 to 1. equivalent to CSS keyframe percentage values:
        offset: [0, 0.499, 0.5, 1],
        // respective CSS property keyframes:
        clipPath: ['inset(0 0 0 0)', 'inset(100% 0 0 0)', 'inset(0 0 100% 0)', 'inset(0 0 0 0)'],
        top: ['0', '-20px', '20px', '0']
      },
      options: {
        duration: 700,
        easing: 'ease'
      }
    });
    
    const attachedAnim = linkTextHoverAnim.toAnimation({
      target: document.querySelector('.link')
    });
    
    attachedAnim.play();
  3. Install KeyframeKit

    KeyframeKit can be installed via npm or imported directly from a CDN.
    npm install keyframekit
    /* Import the module directly via CDN: */
    import KeyframeKit from 'https://unpkg.com/keyframekit/dist/index.min.js'
  4. Import animations from a CSS file

    You can import animations directly from a specific CSS file using KeyframeKit.importStyleSheet(). Note that @import rules within the imported CSS file will not be resolved.
    import KeyframeKit from 'keyframekit';
    
    const styleSheet = await KeyframeKit.importStyleSheet('./styles.css');
    
    const rotateSmallAnimKeyframes = KeyframeKit.getStyleSheetKeyframes({
      of: 'rotate-small',
      in: styleSheet
    });
  5. Play CSS-defined animations using JavaScript

    To play an animation defined in a CSS @keyframes block, use getDocumentStyleSheetsOnLoad() to access the document's stylesheets, getStyleSheetKeyframes() to extract the specific animation, and toKeyframeEffect() to define the timing and easing. Finally, use toAnimation() to attach it to a DOM element.
    import KeyframeKit from 'keyframekit';
    
    // 1. Get document stylesheets
    const documentStyleSheets = await KeyframeKit.getDocumentStyleSheetsOnLoad();
    
    // 2. Convert CSS @keyframes (e.g., 'rotate-small') to Web Animations API keyframes
    const rotateSmallAnimKeyframes = KeyframeKit.getStyleSheetKeyframes({
      of: 'rotate-small',
      in: documentStyleSheets
    });
    
    // 3. Define animation parameters
    const rotateSmallAnim = rotateSmallAnimKeyframes.toKeyframeEffect({
      duration: 700,
      easing: 'ease'
    });
    
    // 4. Attach to element and play
    const attachedAnim = rotateSmallAnim.toAnimation({
      target: document.querySelector('.el')
    });
    
    attachedAnim.play();
    
    // Example of JS playback control:
    attachedAnim.pause();
    attachedAnim.playbackRate = -1; // Reverse playback
    const progress = attachedAnim.overallProgress; // 0 to 1
    await attachedAnim.finished;
  6. Access keyframes and options in KeyframeEffectParameters

    The KeyframeEffectParameters instance exposes the following properties for inspection or modification:
    // The keyframes object
    const frames = keyframeEffectParams.keyframes;
    
    // The keyframe effect options
    const opts = keyframeEffectParams.options;
  7. Extract Web Animations API keyframes from a CSS stylesheet using getStyleSheetKeyframes

    The getStyleSheetKeyframes function retrieves a specific @keyframes rule from a provided CSS stylesheet or stylesheet list and converts it into a format compatible with the Web Animations API (ParsedKeyframes).

    Parameters

    The function accepts a single object with the following properties:

    • in: A CSSStyleSheetSource (either a CSSStyleSheet or a StyleSheetList) where the rule is located.
    • of: A string representing the name of the @keyframes rule to extract.

    Return Value

    • Returns a ParsedKeyframes object if the rule is found.
    • Returns undefined if the rule is not found.

    Error Handling

    • Throws KeyframesRuleNameTypeError if the of parameter is not a string.
    • Throws SourceTypeError if the in parameter is not a CSSStyleSheet or a StyleSheetList.
    function getStyleSheetKeyframes(obj: {
      in: CSSStyleSheetSource;
      of: string;
    }): ParsedKeyframes | undefined;
  8. Convert CSS keyframes rules to Web Animations API keyframes using parseKeyframesRule

    The parseKeyframesRule function in KeyframesFactory takes a standard CSSKeyframesRule object and converts it into a ParsedKeyframes object, making it compatible with the Web Animations API.
    function parseKeyframesRule(keyframesRule: CSSKeyframesRule): ParsedKeyframes;
  9. Extract CSS keyframes using getAllStyleSheetKeyframesRules

    The getAllStyleSheetKeyframesRules function retrieves all CSS keyframes rules from a provided stylesheet or list of stylesheets and converts them into a format compatible with the Web Animations API. It accepts a configuration object containing the in property, which specifies the source stylesheet(s). If the provided source is not a CSSStyleSheet or a StyleSheetList, the function throws a SourceTypeError.
    function getAllStyleSheetKeyframesRules(obj: {
      in: CSSStyleSheetSource;
    }): ParsedKeyframesRules;
  10. Use the KeyframeArgument type for animation keyframes

    The KeyframeArgument type alias defines the acceptable formats for a keyframes object in KeyframeKit. It allows for either an array of Keyframe objects or a PropertyIndexedKeyframes object, aligning with the Web Animations API specifications.
    type KeyframeArgument = Keyframe[] | PropertyIndexedKeyframes;
  11. Import a stylesheet using KeyframesFactory.importStyleSheet

    The importStyleSheet function imports a stylesheet from a specified URL and returns a Promise that resolves to a CSSStyleSheet object. This function serves as a polyfill for CSS Modules in browsers like Safari that do not natively support them.

    Constraints & Caveats:

    • @import rules within the imported stylesheets will not be resolved.
    • Throws a TypeError if the stylesheet cannot be imported.
    function importStyleSheet(url: string): Promise<CSSStyleSheet>;