# All files / draggable useDraggableOrig.ts

0% Statements 0/77
0% Branches 0/1
0% Functions 0/1
0% Lines 0/77

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

     "use client";
    import { useState } from "react";
    import type { UseStateInitializer, UseStateSetter } from "../types.js";
    import {
      useControlledDraggable,
      type BaseDraggableOptions,
      type ControlledDraggableImplementation,
    } from "./useControlledDraggable.js";
    import { getDraggableDefaultValue } from "./utils.js";

    /**
     * @remarks \@since 6.0.0
     */
    export interface DraggableOptions<E extends HTMLElement>
      extends BaseDraggableOptions<E> {
      /**
       * @defaultValue `Math.ceil((max - min) / 2)`
       */
      defaultValue?: UseStateInitializer<number>;
    }

    /**
     * @remarks \@since 6.0.0
     */
    export interface DraggableImplementation<E extends HTMLElement>
      extends ControlledDraggableImplementation<E> {
      /**
       * The current drag distance in pixels.
       */
      value: number;

      /**
       * This can be used to manually set the {@link value} if that is needed for
       * some custom behavior.
       */
      setValue: UseStateSetter<number>;

      /**
       * This will be `true` when the user is dragging the element through mouse or
       * touch.
       */
      dragging: boolean;
    }

    /**
     * This is most likely an internal only hook that provides the functionality for
     * dragging an element through mouse, touch, and keyboard events. The main use
     * cases so far for this hook are:
     * - window splitters
     * - sliders
     *
     * @remarks \@since 6.0.0
     */
    export function useDraggable<E extends HTMLElement>(
      options: DraggableOptions<E>
    ): DraggableImplementation<E> {
      const { min, max, defaultValue, ...dragOptions } = options;
      const [value, setValue] = useState(() =>
        getDraggableDefaultValue({ min, max, defaultValue })
      );
      const [dragging, setDragging] = useState(false);
      const draggable = useControlledDraggable({
        min,
        max,
        dragging,
        setDragging,
        setValue,
        ...dragOptions,
      });

      return {
        ...draggable,
        value,
        setValue,
        dragging,
      };
    }