# All files useCollapseTransition.ts

100% Statements 433/433
100% Branches 26/26
100% Functions 8/8
100% Lines 433/433

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
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    4341x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    102x
    102x
    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
    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
    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
    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
    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
    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
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    92x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    153x
    16x
    16x
    137x
    137x
    137x
    137x
    137x
    137x
    137x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    23x
    23x
    23x
    23x
    23x
    23x
    23x
    879x
    23x
    23x
    23x
    23x
    23x
    23x
    1x
    23x
    23x
    23x
    23x
    23x
    23x
    23x
    23x
    23x
    879x
    27x
    27x
    27x
    879x
    13x
    13x
    13x
    13x
    13x
    13x
    13x
    13x
    13x
    13x
    13x
    13x
    879x
    13x
    13x
    13x
    13x
    13x
    13x
    13x
    13x
    879x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    764x
    764x
    764x
    764x
    764x
    879x
    699x
    693x
    691x
    689x
    4x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
    879x
     "use client";
    import { cnb } from "cnbuilder";
    import type { CSSProperties } from "react";
    import { useState } from "react";
    import { useEnsuredRef } from "../useEnsuredRef.js";
    import { DISPLAY_NONE_CLASS } from "../utils/isElementVisible.js";
    import { collapse } from "./collapseStyles.js";
    import type {
      CSSTransitionElementProps,
      CSSTransitionHookReturnValue,
      PreconfiguredCSSTransitionOptions,
      TransitionTimeout,
      TransitionTimeoutObject,
    } from "./types.js";
    import { useTransition } from "./useTransition.js";
    import { getElementSizing, getTransitionTimeout } from "./utils.js";

    const noop = (): void => {
      // do nothing
    };

    /**
     * @remarks \@since 2.0.0
     */
    export const DEFAULT_COLLAPSE_TIMEOUT: Readonly<TransitionTimeoutObject> = {
      enter: 250,
      exit: 200,
    };

    /**
     * @remarks \@since 4.0.0
     */
    export interface CollapseConfigurationStyle {
      /**
       * The minimum height that the collapsed element can be which defaults to `0`.
       * This can either be a number of pixels or a string CSS height value.
       *
       * Setting this value to any non-zero value will allow for the element to
       * shrink to the defined min-height, and then expand to the full height once
       * no longer collapsed.
       *
       * Note: If the `minHeight`, `minPaddingTop`, and `minPaddingBottom` options
       * are all set to `0` (default), the child will be removed from the DOM while
       * collapsed.
       *
       * @defaultValue `0`
       */
      minHeight?: number | string;

      /**
       * The minimum padding-top that the collapsed element can be which defaults to
       * `0`. This can either be a number of pixels or a string CSS `padding-top`
       * value.
       *
       * Note: If the `minHeight`, `minPaddingTop`, and `minPaddingBottom` options
       * are all set to `0` (default), the child will be removed from the DOM while
       * collapsed.
       *
       * @defaultValue `0`
       */
      minPaddingTop?: number | string;

      /**
       * The minimum padding-bottom that the collapsed element can be which defaults
       * to `0`. This can either be a number of pixels or a string CSS
       * `padding-bottom` value.
       *
       * Note: If the `minHeight`, `minPaddingTop`, and `minPaddingBottom` options
       * are all set to `0` (default), the child will be removed from the DOM while
       * collapsed.
       *
       * @defaultValue `0`
       */
      minPaddingBottom?: number | string;
    }

    /**
     * @remarks \@since 4.0.0
     */
    export interface CollapseStyle extends CollapseConfigurationStyle {
      /**
       * This will only be set when the {@link TransitionStage} is `"entering"` or
       * `"exiting"` as `"${timeout}ms"`.
       */
      transitionDuration?: string;
    }

    /**
     * These props (and `ref`) **must** be passed to a DOM element for the collapse
     * transition to work.
     *
     * @typeParam E - An HTMLElement type used for the ref required for the
     * transition.
     * @remarks \@since 4.0.0
     */
    export interface CollapseElementProps<E extends HTMLElement>
      extends CSSTransitionElementProps<E> {
      /**
       * A merged styled object required for the collapse transition to work.
       *
       * @see {@link CollapseStyle}
       * @see {@link CollapseTransitionHookOptions.style}
       */
      style: CSSProperties;
    }

    /**
     * @typeParam E - An HTMLElement type used for the ref required for the
     * transition.
     * @remarks \@since 4.0.0
     */
    export interface CollapseTransitionHookOptions<E extends HTMLElement>
      extends Omit<PreconfiguredCSSTransitionOptions<E>, "exitedHidden">,
        CollapseConfigurationStyle {
      /**
       * An optional style to merge with the required collapse transition styles.
       *
       * If any keys from the {@link CollapseStyle} are included in this object,
       * these styles will override and possibly break the collapse transition.
       */
      style?: CSSProperties;

      /**
       *
       * @see {@link DEFAULT_COLLAPSE_TIMEOUT}
       * @defaultValue `DEFAULT_COLLAPSE_TIMEOUT`
       */
      timeout?: TransitionTimeout;

      /**
       *
       * @defaultValue `minHeight === 0 && minPaddingTop === 0 && minPaddingBottom === 0`
       */
      temporary?: boolean;
    }

    /**
     * @typeParam E - An HTMLElement type used for the ref required for the
     * transition.
     * @remarks \@since 4.0.0
     */
    export interface CollapseTransitionHookReturnValue<E extends HTMLElement>
      extends CSSTransitionHookReturnValue<E>,
        CollapseElementProps<E> {
      /**
       * This is just a convenience object so that you don't need to destructure as
       * many variables to pass to an element.
       *
       * @example
       * Simple Usage
       * ```tsx
       * const { elementProps, rendered } = useCollapseTransition({
       *   // ...options
       *   transitionIn,
       * });
       *
       * if (!rendered) {
       *   return null
       * }
       *
       * return <div {...elementProps}>{children}</div>;
       *
       * // This is the long-hand version
       * const { ref, style, className, hidden, rendered } = useCollapseTransition({
       *   // ...options
       *   transitionIn,
       * });
       *
       * if (!rendered) {
       *   return null
       * }
       *
       * return (
       *   <div
       *     ref={ref}
       *     style={style}
       *     className={className}
       *     hidden={hidden}
       *   >
       *     {children}
       *   </div>
       * );
       * ```
       */
      elementProps: Readonly<CollapseElementProps<E>>;
    }

    /**
     * This hook is used to create a transition to collapse and expand an element
     * **inline** with other content like an accordion by animating the
     * `max-height`, `padding-top`, and `padding-bottom` CSS properties. The default
     * behavior is to hide the element completely while collapsed, but providing the
     * `minHeight`, `minPaddingTop`, and `minPaddingBottom` options can make this
     * work like a "See More"/"Preview" type of element
     *
     * @example
     * Simple Example
     * ```tsx
     * import { ReactElement, useState } from "react";
     * import { Button, Typography, useCollapseTransition } from "@react-md/core";
     *
     * function Example(): ReactElement {
     *   const [collapsed, setCollapsed] = useState(true);
     *   const { elementProps, rendered } =
     *     useCollapseTransition({
     *       transitionIn: !collapsed,
     *       // If the collapsible element should maintain state by not unmounting
     *       // while collapsed, uncomment this next line
     *       // temporary: false,
     *     });
     *
     *   return (
     *     <>
     *       <Button onClick={() => setCollapsed(!collapsed)}>
     *         Toggle
     *       </Button>
     *       {rendered && (
     *         <div {...elementProps}>
     *           <Typography>Stuff that should be collapsed</Typography>
     *           <div>Whatever content...</div>
     *         </div>
     *       )}
     *     </>
     *   );
     * }
     * ```
     *
     * @example
     * See More Example
     * ```tsx
     * import { ReactElement, useState } from "react";
     * import { Button, IconRotator, Typography, useCollapseTransition } from "@react-md/core";
     * import { KeyboardArrowDownSVGIcon } from "@react-md/material-icons";
     *
     * import styles from "./Example.module.scss";
     * // pretend styles:
     * //
     * // .container {
     * //   padding: 1rem;
     * //   position: relative;
     * // }
     * //
     * // .button {
     * //   position: absolute;
     * //   right: 0;
     * //   top: 0;
     * // }
     *
     *
     * function Example(): ReactElement {
     *   const [collapsed, setCollapsed] = useState(true);
     *   const { elementProps } =
     *     useCollapseTransition({
     *       transitionIn: !collapsed,
     *       minHeight: 120,
     *       minPaddingTop: 16,
     *       className: styles.container,
     *     });
     *
     *   return (
     *     <div {...elementProps}>
     *       <Button
     *         aria-expanded={!collapsed}
     *         aria-label="Expand"
     *         onClick={() => setCollapsed(!collapsed)}
     *         buttonType="icon"
     *         className={styles.button}
     *       >
     *         <IconRotator rotated={!collapsed}>
     *           <KeyboardArrowDownSVGIcon />
     *         </IconRotator>
     *       </Button>
     *       <SomeComponentWithALotOfContent />
     *     </div>
     *   );
     * }
     * ```
     *
     * @typeParam E - An HTMLElement type used for the ref required for the
     * transition.
     * @remarks \@since 4.0.0
     */
    export function useCollapseTransition<E extends HTMLElement>(
      options: CollapseTransitionHookOptions<E>
    ): CollapseTransitionHookReturnValue<E> {
      const {
        nodeRef: propNodeRef,
        style: propStyle,
        className,
        transitionIn,
        timeout = DEFAULT_COLLAPSE_TIMEOUT,
        minHeight = 0,
        minPaddingTop = 0,
        minPaddingBottom = 0,
        temporary = minHeight === 0 &&
          minPaddingTop === 0 &&
          minPaddingBottom === 0,
        appear = false,
        enter = true,
        exit = true,
        onEnter = noop,
        onEntering = noop,
        onEntered = noop,
        onExit = noop,
        onExiting = noop,
        onExited = noop,
      } = options;

      const [nodeRef, refCallback] = useEnsuredRef(propNodeRef);
      const [style, setStyle] = useState<CSSProperties | undefined>(() => {
        if (transitionIn) {
          return undefined;
        }

        return {
          maxHeight: minHeight,
          paddingTop: minPaddingTop,
          paddingBottom: minPaddingBottom,
        };
      });

      const transitionTimeout = getTransitionTimeout({
        timeout,
        appear,
        enter,
        exit,
      });

      const { appearing, rendered, ref, stage, transitionTo, disablePortal } =
        useTransition({
          nodeRef: refCallback,
          timeout,
          transitionIn,
          reflow: true,
          appear,
          enter,
          exit,
          temporary,
          onEnter(appearing) {
            onEnter(appearing);
            setStyle({
              maxHeight: minHeight,
              paddingTop: minPaddingTop,
              paddingBottom: minPaddingBottom,
            });
          },
          onEntering(appearing) {
            onEntering(appearing);
            const { maxHeight, paddingTop, paddingBottom } = getElementSizing(
              nodeRef.current
            );

            const duration = appearing
              ? transitionTimeout.appear
              : transitionTimeout.enter;

            setStyle({
              maxHeight,
              paddingTop,
              paddingBottom,
              transitionDuration: `${duration}ms`,
            });
          },
          onEntered(appearing) {
            onEntered(appearing);
            setStyle(undefined);
          },
          onExit() {
            onExit();
            const { maxHeight, paddingTop, paddingBottom } = getElementSizing(
              nodeRef.current
            );

            setStyle({
              maxHeight,
              paddingTop,
              paddingBottom,
              transitionDuration: `${transitionTimeout.exit}ms`,
            });
          },
          onExiting() {
            onExiting();
            setStyle({
              maxHeight: minHeight,
              paddingTop: minPaddingTop,
              paddingBottom: minPaddingBottom,
              transitionDuration: `${transitionTimeout.exit}ms`,
            });
          },
          onExited() {
            onExited();
            setStyle({
              maxHeight: minHeight,
              paddingTop: minPaddingTop,
              paddingBottom: minPaddingBottom,
            });
          },
        });
      const entering = stage === "enter" || stage === "entering";
      const exiting = stage === "exit" || stage === "exiting";
      const collapsible =
        transitionTimeout.enter !== 0 || transitionTimeout.exit !== 0;

      const elementProps: CollapseElementProps<E> = {
        ref,
        style: { ...style, ...propStyle },
        className:
          cnb(
            className,
            collapsible &&
              collapse({
                enter: entering,
                leave: exiting,
                disableOverflow: !transitionIn || !!style,
              }),
            stage === "exited" &&
              minHeight === 0 &&
              minPaddingTop === 0 &&
              minPaddingBottom === 0 &&
              DISPLAY_NONE_CLASS
          ) || undefined,
      };

      return {
        ...elementProps,
        stage,
        rendered,
        appearing,
        elementProps,
        transitionTo,
        disablePortal,
      };
    }