use-scramble

repository·main·Indexed 40 days ago

https://github.com/tol-is/use-scramble

A lightweight (1KB) React hook for high-performance random text animations, providing scrambling and typewriter effects. Version 2.2.15 features a configurable animation engine with controls for speed, tick rate, and Unicode character ranges, as well as built-in support for prefers-reduced-motion accessibility settings.

Tokens
3.7K
Snippets
7
Records
11
Agent score
0%

What's inside use-scramble

  1. How useScramble works

    main

    The useScramble hook provides a ref object that must be attached to a target DOM node (e.g., a <p> or <div>) for the text animation to take control of that element. By default, the animation starts automatically when the component mounts. You can customize the animation's pace, style, and character set via the configuration object.

    import { useScramble } from 'use-scramble';
    
    export const App = () => {
      const { ref } = useScramble({
        text: 'Achilles next, that nimble runner, swift on his feet as the wind',
        speed: 0.6,
        tick: 1,
        step: 1,
        scramble: 4,
        seed: 0,
      });
    
      return <p ref={ref} />;
    };
  2. Respecting reduced motion preferences

    main
    The useScramble library automatically respects user accessibility settings. If a user has enabled prefers-reduced-motion: reduce in their system/browser settings, the animation is entirely disabled.
  3. Manually replay animations with the replay function

    main

    The useScramble hook returns a replay function. You can use this to trigger the animation manually (e.g., on hover or click). To prevent the animation from running automatically when the component first loads, set playOnMount: false in the configuration.

    import { useScramble } from 'use-scramble';
    
    export const App = () => {
      const { ref, replay } = useScramble({
        text: 'Achilles next, that nimble runner, swift on his feet as the wind',
        playOnMount: false
      });
    
      return <p ref={ref} onMouseOver={replay} onMouseOut={replay} />;
    };
  4. How `useScramble` handles reduced motion

    main

    The useScramble hook automatically detects if the user has enabled prefers-reduced-motion: reduce via the browser's media query.

    If reduced motion is detected, the hook modifies the animation parameters to prevent rapid flickering:

    • step is set to the full length of the text (skipping the incremental animation).
    • chance is set to 0 (no scrambling).
    • overdrive is set to false.
  5. useScramble return values

    main

    The useScramble hook returns an object containing:

    • ref: A React ref to be attached to the target DOM element.
    • replay: A function that, when called, restarts the animation.
    const { ref, replay } = useScramble({ text: 'your_text' });
    
    return <p ref={ref} onClick={replay} />;
  6. Configure `useScramble` with `UseScrambleProps`

    main

    The useScramble hook accepts an optional UseScrambleProps object to customize the animation behavior.

    Animation Timing & Speed

    • speed (number, default: 1): A 0-1 range determining scramble speed. 1 redraws ~60 times per second. 0 pauses the animation.
    • tick (number, default: 1): Controls how many frames pass before the controller moves forward along the text.
    • step (number, default: 1): How many characters to step forward on every tick.
    • playOnMount (boolean, default: true): If true, the animation will not play the first time text is provided (it will wait for a change or manual trigger).

    Scramble Logic

    • text (string, default: ''): The target text to scramble towards.
    • scramble (number, default: 1): How many times to scramble each character.
    • chance (number, default: 1): Probability (0 to 1) of a character being scrambled.
    • seed (number, default: 1): Number of characters to randomize at random text positions.
    • ignore (string[], default: [' ']): Characters that should not be scrambled.
    • range (RangeOrCharCodes, default: [65, 125]): Unicode character range for the scrambler. Can be a tuple [min, max] or an array of specific character codes.
    • overdrive (boolean | number, default: true): If true, enables overdrive mode. If a number is provided, that Unicode character code is used during overdrive.
    • overflow (boolean, default: true): If true, the animation always starts from an empty string.

    Callbacks

    • onAnimationStart (Function): Called when the animation begins drawing.
    • onAnimationEnd (Function): Called when the animation finishes (result matches input text).
    • onAnimationFrame ((result: string) => void): Called on every redraw with the current scrambled string.
  7. Reference: Unicode values for scramble range

    main

    When configuring the range property, you can use these Unicode values to define the pool of characters used for scrambling. Common values include:

    • 32: Space
    • 48-57: Digits 0-9
    • 65-90: Latin Capital letters A-Z
    • 97-122: Latin Small letters a-z
    • 33-47: Various punctuation marks
    | Glyph | Unicode | Description |
    | ------ | ------ | :--- |
    | &nbsp; | 32 | Space mark |
    | ! | 33 | Exclamation mark |
    | " | 34 | Quotation mark |
    | # | 35 | Hash |
    | $ | 36 | Dollar sign |
    | % | 37 | Percent sign |
    | & | 38 | Ampersand |
    | ' | 39 | Apostrophe |
    | ( | 40 | Left parenthesis |
    | ) | 41 | Right parenthesis |
    | * | 42 | Asterisk |
    | + | 43 | Plus sign |
    | , | 44 | Comma |
    | - | 45 | Hyphen-minus |
    | . | 46 | Full stop |
    | / | 47 | Slash (Solidus) |
    | 0 | 48 | Digit Zero |
    | 1 | 49 | Digit One |
    | 2 | 50 | Digit Two |
    | 3 | 51 | Digit Three |
    | 4 | 52 | Digit Four |
    | 5 | 53 | Digit Five |
    | 6 | 54 | Digit Six |
    | 7 | 55 | Digit Seven |
    | 8 | 56 | Digit Eight |
    | 9 | 57 | Digit Nine |
    | : | 58 | Colon |
    | ; | 59 | Semicolon |
    | < | 60 | Less-than sign |
    | = | 61 | Equal sign |
    | > | 62 | Greater-than sign |
    | ? | 63 | Question mark |
    | @ | 64 | At sign |
    | A | 65 | Latin Capital letter A |
    | B | 66 | Latin Capital letter B |
    | C | 67 | Latin Capital letter C |
    | D | 68 | Latin Capital letter D |
    | E | 69 | Latin Capital letter E |
    | F | 70 | Latin Capital letter F |
    | G | 71 | Latin Capital letter G |
    | H | 72 | Latin Capital letter H |
    | I | 73 | Latin Capital letter I |
    | J | 74 | Latin Capital letter J |
    | K | 75 | Latin Capital letter K |
    | L | 76 | Latin Capital letter L |
    | M | 77 | Latin Capital letter M |
    | N | 78 | Latin Capital letter N |
    | O | 79 | Latin Capital letter O |
    | P | 80 | Latin Capital letter P |
    | Q | 81 | Latin Capital letter Q |
    | R | 82 | Latin Capital letter R |
    | S | 83 | Latin Capital letter S |
    | T | 84 | Latin Capital letter T |
    | U | 85 | Latin Capital letter U |
    | V | 86 | Latin Capital letter V |
    | W | 87 | Latin Capital letter W |
    | X | 88 | Latin Capital letter X |
    | Y | 89 | Latin Capital letter Y |
    | Z | 90 | Latin Capital letter Z |
    | [ | 91 | Left Square Bracket |
    | \ | 92 | Backslash |
    | ] | 93 | Right Square Bracket |
    | ^ | 94 | Circumflex accent |
    | _ | 95 | Low line |
    | ` | 96 | Grave accent |
    | a | 97 | Latin Small Letter A |
    | b | 98 | Latin Small Letter B |
    | c | 99 | Latin Small Letter C |
    | d | 100 | Latin Small Letter D |
    | e | 101 | Latin Small Letter E |
    | f | 102 | Latin Small Letter F |
    | g | 103 | Latin Small Letter G |
    | h | 104 | Latin Small Letter H |
    | i | 105 | Latin Small Letter I |
    | j | 106 | Latin Small Letter J |
    | k | 107 | Latin Small Letter K |
    | l | 108 | Latin Small Letter L |
    | m | 109 | Latin Small Letter M |
    | n | 110 | Latin Small Letter N |
    | o | 111 | Latin Small Letter O |
    | p | 112 | Latin Small Letter P |
    | q | 113 | Latin Small Letter Q |
    | r | 114 | Latin Small Letter R |
    | s | 115 | Latin Small Letter S |
    | t | 116 | Latin Small Letter T |
    | u | 117 | Latin Small Letter U |
    | v | 118 | Latin Small Letter V |
    | w | 119 | Latin Small Letter W |
    | x | 120 | Latin Small Letter X |
    | y | 121 | Latin Small Letter Y |
    | z | 122 | Latin Small Letter Z |
    | { | 123 | Left Curly Bracket |
    | | | 124 | Vertical bar |
    | } | 125 | Right Curly Bracket |
    | ~ | 126 | Tilde |
  8. useScramble configuration options

    main

    The useScramble hook accepts an options object to customize the animation behavior.

    Propertytypedefaultrangedescription
    playOnMountbooleantrueSkip the animation on the first mount input
    textstring-Set the text value of the animation. The animation will start automatically
    speednumber10-1Internal clock framerate. 1 will tick 60 times a second. 0 will pause the animation
    ticknumber11-∞Controls how many ticks pass for an animation redraw. Combined with speed, you can fully control the pace rate
    stepnumber11-∞Controls the animation step. On every redraw, the algorithm moves forward by step characters
    scramblenumber10-∞Controls how many times to randomize each character. A value of 0 will emulate a typewriter effect
    seednumber10-∞Adds randomized characters ahead of the animation step, animating characters across the text block
    chancenumber10-1Chance of scrambling a character, range from 0 to 1, 0 being no chance, and 1 being 100% chance
    rangenumber[][65,125]Unicode characters range to select random characters from
    overdrivebooleantrueDefaults to underscore (95) unicode character, or provide a custom unicode value
    overflowbooleantrueIf true, animates over the previous text. If false, resets the text contents and restarts from an empty string
    ignorestring[][" "]Ignore specific characters when animating. Default is only spaces to maintain text shape
    onAnimationStartfunction-Callback invoked when the animation starts playing
    onAnimationFramefunction-Callback invoked on every redraw
    onAnimationEndfunction-Callback invoked when the animation ends
  9. Use the `useScramble` hook

    main

    The useScramble hook provides a React hook to create a text scrambling animation effect. It returns a ref to be attached to a DOM element (which will have its innerHTML updated by the animation) and a replay function to manually restart the animation.

    To use it, pass a UseScrambleProps configuration object to the hook and attach the returned ref to an element, such as a <div> or <span>.

    import { useScramble } from 'use-scramble';
    
    const MyComponent = () => {
      const { ref, replay } = useScramble({
        text: 'Hello World',
        speed: 1,
      });
    
      return (
        <div>
          <h1 ref={ref}></h1>
          <button onClick={replay}>Replay Animation</button>
        </div>
      );
    };
  10. Configure the Unicode character range for scrambling

    main

    The range property in UseScrambleProps defines which Unicode characters are used during the scramble effect. It accepts a RangeOrCharCodes type:

    1. A Range (Tuple): Provide a two-element array [min, max] (e.g., [65, 125]) to pick random characters within that Unicode range.
    2. Specific Characters (Array): Provide an array of numbers representing specific Unicode character codes (e.g., [33, 35, 38]). The scrambler will pick randomly only from these values.

    Note: To simulate a range using the array method, you can repeat values, e.g., [91, 93, 91, 93].

    // Using a range
    const props = { range: [65, 125] } as UseScrambleProps;
    
    // Using specific characters
    const props = { range: [33, 35, 38, 42] } as UseScrambleProps;