# All files / transition useSkeletonPlaceholder.ts

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

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

     "use client";
    import { cnb } from "cnbuilder";
    import { useEffect, useState, type CSSProperties } from "react";
    import { useSsr } from "../SsrProvider.js";
    import {
      randomSkeletonPlaceholder,
      skeletonPlaceholder,
      type SkeletonPlaceholderRandomOptions,
    } from "./skeletonPlaceholderUtils.js";

    /** @remarks \@since 6.0.0 */
    export interface SkeletonPlaceholderOptions
      extends SkeletonPlaceholderRandomOptions {
      style?: CSSProperties;
      className?: string;

      /**
       * Set this to a custom `animation-delay` value (should be in milliseconds).
       *
       * @example
       * ```ts
       * delay="200ms"
       * ```
       */
      delay?: string;

      /**
       * Set this value tp a number or length unit string to set the height with
       * inline styles.
       *
       * If this is `undefined`, it will use the skeleton placeholder CSS variable
       * value instead which defaults to `1.125em`
       *
       * @defaultValue `undefined`
       */
      height?: string | number;

      /**
       * A custom width to apply to the skeleton placeholder.
       *
       * Set this value to an empty string if you want to control the width through
       * SCSS.
       *
       * @example
       * No Inline Width CSS
       * ```scss
       * @use "@react-md/core";
       *
       * .customStyles {
       *   // You could use these mixins on a parent element instead which would
       *   // set the height and width to all skeleton placeholders that appear as a
       *   // child instead
       *   // @include core.transition-set-var(skeleton-placeholder-height, 1.5rem);
       *   // @include core.transition-set-var(skeleton-placeholder-width, 40%);
       *
       *   height: 1,5rem;
       *   width: 40%;
       * }
       * ```
       *
       * @example
       * No Inline Width
       * ```ts
       * import type { ReactElement } from "@react";
       * import { useSkeletonPlaceholder } from "@react-md/core";
       *
       * import styles from "./MyComponent.module.scss";
       *
       * export function Example(): ReactElement {
       *   const skeletonProps = useSkeletonPlaceholder({
       *     width: null,
       *     className: styles.customStyles,
       *   });
       *
       *   return <div {...skeletonProps} />;
       * }
       * ```
       *
       *
       * Set this value to a number or length unit string to set the width with
       * inline styles.
       *
       * @example
       * Custom Inline Width
       * ```ts
       * import type { ReactElement } from "@react";
       * import { useSkeletonPlaceholder } from "@react-md/core";
       *
       * export function Example(): ReactElement {
       *   const skeletonProps = useSkeletonPlaceholder({
       *     // any of these are valid
       *     // width: 40,
       *     // width: "1rem",
       *     // width: "1vh",
       *     // width: "40%",
       *     width: "1rem",
       *   });
       *
       *   return <div {...skeletonProps} />;
       * }
       * ```
       *
       * If this value is `undefined`, a random percentage will be generated instead
       * using the {@link minPercentage} and {@link maxPercentage} options.
       *
       * Set this value to `null` if the size should be derived from the provided
       * `className` instead.
       *
       * @defaultValue `randomInt({ min: minPercentage, max: maxPercentage })%`
       */
      width?: number | string | null;

      /**
       * Settings this to `true` will prevent any of the skeleton placeholder styles
       * to be applied. This is really only useful if you can prerender parts of
       * your layout while waiting for the data to load.
       *
       * @example
       * Pre-rendered Layout
       * ```tsx
       * import type { ReactElement } from "@react";
       * import { SkeletonPlaceholder } from "@react-md/core";
       *
       * interface Data {
       *   id: string;
       *   name: string;
       *   createdBy: string
       *   createdOn: string;
       *   modifiedBy: string;
       *   modifiedOn: string;
       * }
       *
       * function ShowData({
       *   id,
       *   name,
       *   createdBy,
       *   createdOn,
       *   modifiedBy,
       *   modifiedOn,
       * }: Partial<Data>:: ReactElement {
       *   const loading =
       *     !name &&
       *     !createdBy &&
       *     !createdOn &&
       *     !modifiedBy &&
       *     !modifiedOn;
       *
       *   return (
       *     <Box grid gridClassName="custom-class-name">
       *       <SkeletonPlaceholder disabled={!loading}>
       *         {id}
       *       </SkeletonPlaceholder>
       *       <SkeletonPlaceholder disabled={!loading}>
       *         {name}
       *       </SkeletonPlaceholder>
       *       <SkeletonPlaceholder disabled={!loading}>
       *         {createdOn}
       *       </SkeletonPlaceholder>
       *       <SkeletonPlaceholder disabled={!loading}>
       *         {createdBy}
       *       </SkeletonPlaceholder>
       *       <SkeletonPlaceholder disabled={!loading}>
       *         {modifiedOn}
       *       </SkeletonPlaceholder>
       *       <SkeletonPlaceholder disabled={!loading}>
       *         {modifiedBy}
       *       </SkeletonPlaceholder>
       *     </Box>
       *   );
       * }
       *
       * export function Example(): ReactElement {
       *   const { data } = useLoadSomeDataQuery();
       *
       *   const items = useMemo(() => {
       *     // if the data has been fetched, just return the data
       *     if (data) {
       *       return data;
       *     }
       *
       *     // if the data does not exist, set up a skeleton of your layout by
       *     // rendering a random number of items.
       *     //
       *     // NOTE: This is memoized so you don't create a random length each
       *     // render
       *     const length = randomInt({ min: 3, max: 10 })
       *     return Array.from({ length }, (_, i) => ({ id: `placeholder-${i}` }));
       *   }, [data])
       *
       *   return (
       *     <List>
       *       {items.map((item) => <ShowData {...item} />)}
       *     </List>
       *   );
       * }
       * ```
       *
       * @defaultValue `false`
       */
      disabled?: boolean;
    }

    export interface SkeletonPlaceholderStylingProps {
      style?: CSSProperties;
      className: string;
    }

    export function useSkeletonPlaceholder(
      options: SkeletonPlaceholderOptions = {}
    ): SkeletonPlaceholderStylingProps {
      const {
        style: propStyle,
        className,
        height,
        width: propWidth,
        disabled = false,
        delay: propDelay,
        minDelay,
        maxDelay,
        minPercentage,
        maxPercentage,
      } = options;
      const ssr = useSsr();

      const isDefinedWidth = typeof propWidth !== "undefined";
      const isDefinedDelay = typeof propDelay !== "undefined";
      const [randomStyles, setRandomStyles] = useState<CSSProperties>(() => {
        if (typeof window === "undefined" || ssr || disabled) {
          return {};
        }

        return randomSkeletonPlaceholder({
          minDelay,
          maxDelay,
          minPercentage,
          maxPercentage,
        });
      });

      useEffect(() => {
        if (!ssr || disabled || (isDefinedDelay && isDefinedWidth)) {
          return;
        }

        setRandomStyles(
          randomSkeletonPlaceholder({
            minDelay,
            maxDelay,
            minPercentage,
            maxPercentage,
          })
        );
      }, [
        disabled,
        isDefinedDelay,
        isDefinedWidth,
        maxDelay,
        maxPercentage,
        minDelay,
        minPercentage,
        ssr,
      ]);

      let width = propWidth;
      let animationDelay = propDelay;
      if (!isDefinedDelay) {
        ({ animationDelay } = randomStyles);
      }
      if (!isDefinedWidth) {
        ({ width } = randomStyles);
      }

      let style: CSSProperties | undefined = propStyle;
      if (!!width || !!animationDelay || typeof height !== "undefined") {
        style = {
          ...style,
          height: height ?? style?.height,
          width: width ?? style?.width,
          // Note: not including MozAnimationDelay and WebkitAnimationDelay since
          // they weren't applied when they were set. Probably no longer required?
          animationDelay: animationDelay ?? style?.animationDelay,
        };
      }

      return {
        style,
        className: cnb(className, !disabled && skeletonPlaceholder()),
      };
    }