# All files / src/utils parseCssLengthUnit.ts

100% Statements 65/65
100% Branches 13/13
100% Functions 1/1
100% Lines 65/65

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
    661x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    126x
    126x
    126x
    6x
    6x
    120x
    120x
    126x
    4x
    4x
    116x
    121x
    5x
    5x
    111x
    111x
    126x
    126x
    126x
    126x
    126x
    126x
    126x
    126x
     /** @internal */
    export interface ParseCssLengthUnitOptions {
      /**
       *
       */
      value: number | string;

      /**
       * @defaultValue `16`
       */
      fallbackFontSize?: number;

      /**
       * @defaultValue `document.documentElement`
       */
      container?: Element | null;
    }

    /**
     * This is used to convert CSS length units into a number. At this time, it really only supports
     * - `px`
     * - `rem`
     * - `em` (if {@link ParseCssLengthUnitOptions.container} is provided)
     *
     * @example
     * Simple Example
     * ```ts
     * parseCssLengthUnit({ value: "24px" }) // 24
     * parseCssLengthUnit({ value: "3.5rem" }) // 56
     * parseCssLengthUnit({
     *   value: "3em",
     *   container: document.querySelector(SOME_QUERY),
     * }); // container's computed fontSize * 3
     * ```
     *
     * @see {@link https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Values_and_units#lengths}
     * @internal
     * @remarks
     * \@since 6.0.0 This was renamed from `unitToNumber`
     */
    export function parseCssLengthUnit(options: ParseCssLengthUnitOptions): number {
      const { value, container, fallbackFontSize = 16 } = options;

      if (typeof value === "number") {
        return value;
      }

      const parsed = parseFloat(value);
      if (/px$/i.test(value)) {
        return parsed;
      }

      if (typeof window === "undefined") {
        return parsed * fallbackFontSize;
      }

      const styleContainer =
        !container || /rem$/i.test(value) ? document.documentElement : container;

      const fontSize = parseFloat(
        window.getComputedStyle(styleContainer).fontSize || `${fallbackFontSize}px`
      );

      return parsed * fontSize;
    }