# All files / expansion-panel useExpansionPanels.ts

99.64% Statements 280/281
95.83% Branches 23/24
100% Functions 4/4
99.64% Lines 280/281

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
    2821x
    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
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    6x
    5x
    5x
    4x
    4x
    5x
    5x
    5x
    1x
    1x
    1x
    1x

    6x
    6x
    15x
    15x
    15x
    15x
    15x
    45x
    45x
    45x
    42x
    42x
    45x
    3x
    3x
    45x
    45x
    45x
    45x
    45x
    45x
    45x
    45x
    45x
    9x
    1x
    1x
    8x
    8x
    8x
    8x
    6x
    6x
    2x
    2x
    8x
    1x
    1x
    1x
    1x
    2x
    2x
    2x
    8x
    45x
    45x
    45x
    45x
    15x
    15x
     "use client";
    import { useState } from "react";
    import type { UseStateInitializer, UseStateSetter } from "../types.js";
    import { useEnsuredId } from "../useEnsuredId.js";
    import type { ExpansionPanelProps } from "./ExpansionPanel.js";

    /** @remarks \@since 6.0.0 */
    export interface ExpansionPanelHookOptions {
      /**
       * An optional id to prefix each panel with.
       *
       * @defaultValue `"expansion-panel-" + useId()`
       */
      baseId?: string;

      /**
       * Set this to `true` if multiple panels can be open at the same time.
       *
       * @defaultValue `false`
       */
      multiple?: boolean;

      /**
       * Set this to `true` to enforce that at least one panel must always be
       * expanded.
       *
       * @defaultValue `false`
       */
      preventAllCollapsed?: boolean;

      /**
       * This is a convenience option to disable the expansion transition for all
       * panels.
       *
       * @defaultValue `false`
       */
      disableTransition?: boolean;

      /**
       * @defaultValue `preventAllCollapsed ? ["expansion-panel-" + useId() + "-1"] : []`
       */
      defaultExpandedIds?: UseStateInitializer<string[]>;

      /**
       * This can only be used if the {@link defaultExpandedIds} was not provided
       * and using index based panels.
       *
       * @example
       * ```tsx
       * const { getPanelProps } = useExpansionPanels({
       *   defaultExpandedIndex: 2,
       * });
       *
       * return (
       *   <ExpansionPanel {...getPanelProps(0)} />
       *   <ExpansionPanel {...getPanelProps(1)} />
       *   // expanded on first render
       *   <ExpansionPanel {...getPanelProps(2)} />
       *   <ExpansionPanel {...getPanelProps(3)} />
       * );
       * ```
       */
      defaultExpandedIndex?: number;

      /**
       * @defaultValue `false`
       */
      disableContentPadding?: boolean;
    }

    /** @remarks \@since 6.0.0 */
    export type ProvidedExpansionPanelProps = Pick<
      Required<ExpansionPanelProps>,
      | "disabled"
      | "expanded"
      | "onExpandClick"
      | "disableTransition"
      | "disableContentPadding"
    > & { id?: string };

    /**
     * @param indexOrPanelId - This should either be a DOM id to use for the panel
     * or the panel's index.
     * @returns Props to pass to an `ExpansionPanel` for it to work correctly.
     * @remarks \@since 6.0.0
     */
    export type GetExpansionPanelProps = (
      indexOrPanelId: string | number
    ) => ProvidedExpansionPanelProps;

    /** @remarks \@since 6.0.0 */
    export interface ExpansionPanelImplementation {
      /**
       * The current set of expanded panel ids if you need this for some reason.
       */
      expandedIds: ReadonlySet<string>;

      /**
       * This can be used to manually control which panels are expanded if the
       * default behavior does not work for your use case.
       */
      setExpandedIds: UseStateSetter<ReadonlySet<string>>;

      /**
       * @example
       * Index Based Panels
       * ```tsx
       * <ExpansionPanel {...getPanelProps(0)} />
       * <ExpansionPanel {...getPanelProps(1)} />
       * <ExpansionPanel {...getPanelProps(2)} />
       * ```
       *
       * @example
       * Custom Panel Ids
       * ```tsx
       * <ExpansionPanel {...getPanelProps("address-panel")} />
       * <ExpansionPanel {...getPanelProps("billing-panel")} />
       * <ExpansionPanel {...getPanelProps("confirmation-panel")} />
       * ```
       */
      getPanelProps: GetExpansionPanelProps;
    }

    /**
     * Use this hook to control the expanded state for a group of `ExpansionPanel`.
     *
     * @example
     * Index Based Panels
     * ```tsx
     * import {
     *   ExpansionList,
     *   ExpansionPanel,
     *   useExpansionPanels,
     * } from "@react-md/core";
     * import { type ReactElement } from "react";
     *
     * function Example(): ReactElement {
     *   const { getPanelProps } = useExpansionPanels();
     *
     *   return (
     *     <ExpansionList>
     *       <ExpansionPanel {...getPanelProps(0)} headerChildren="Panel 1">
     *         Panel 1 Contents
     *       </ExpansionPanel>
     *       <ExpansionPanel {...getPanelProps(1)} headerChildren="Panel 2">
     *         Panel 2 Contents
     *       </ExpansionPanel>
     *       <ExpansionPanel {...getPanelProps(2)} headerChildren="Panel 3">
     *         Panel 3 Contents
     *       </ExpansionPanel>
     *     </ExpansionList>
     *   );
     * }
     * ```
     *
     * @example
     * Custom Panel Ids and Expand All Panels by Default
     * ```tsx
     * import {
     *   ExpansionList,
     *   ExpansionPanel,
     *   useExpansionPanels,
     * } from "@react-md/core";
     * import { type ReactElement } from "react";
     *
     * import { BillingAddress } from "./BillingAddress";
     * import { BillingInformation } from "./BillingInformation";
     * import { PersonalInformation } from "./PersonalInformation";
     *
     * const panel1Id = "personal-information-panel";
     * const panel2Id = "billing-information-panel";
     * const panel3Id = "billing-address-panel";
     *
     * function Example(): ReactElement {
     *   const { getPanelProps } = useExpansionPanels({
     *     multiple: true,
     *     defaultExpandedIds: () => [panel1Id, panel2Id, panel3Id],
     *   });
     *
     *   return (
     *     <ExpansionList>
     *       <ExpansionPanel {...getPanelProps(panel1Id)} headerChildren="Personal Information">
     *         <PersonalInformation />
     *       </ExpansionPanel>
     *       <ExpansionPanel {...getPanelProps(panel2Id)} headerChildren="Billing Information">
     *         <BillingInformation />
     *       </ExpansionPanel>
     *       <ExpansionPanel {...getPanelProps(panel3Id)} headerChildren="Billing Address">
     *         <BillingAddress />
     *       </ExpansionPanel>
     *     </ExpansionList>
     *   );
     * }
     * ```
     *
     *
     * @remarks
     * \@since 6.0.0 The hook was renamed from `usePanels` to `useExpansionPanels`,
     * the API changed to return `getPanelProps` instead of a generated list of
     * panel props based on the provided `count`, and the hook no longer supports
     * having all panels expanded by default.
     */
    export function useExpansionPanels(
      options: ExpansionPanelHookOptions = {}
    ): ExpansionPanelImplementation {
      const {
        baseId: propBaseId,
        multiple = false,
        preventAllCollapsed = false,
        disableTransition = false,
        defaultExpandedIds,
        defaultExpandedIndex,
        disableContentPadding = false,
      } = options;

      const baseId = useEnsuredId(propBaseId, "expansion-panel");
      const createId = (index: number): string => `${baseId}-${index + 1}`;
      const [expandedIds, setExpandedIds] = useState<ReadonlySet<string>>(() => {
        if (typeof defaultExpandedIds === "undefined") {
          const initialList: string[] = [];
          if (typeof defaultExpandedIndex === "number" || preventAllCollapsed) {
            initialList.push(createId(defaultExpandedIndex ?? 0));
          }

          return new Set(initialList);
        }

        const ids =
          typeof defaultExpandedIds === "function"
            ? defaultExpandedIds()
            : defaultExpandedIds;
        return new Set(ids);
      });

      return {
        expandedIds,
        setExpandedIds,
        getPanelProps(indexOrPanelId) {
          let id: string | undefined;
          let panelId: string;
          if (typeof indexOrPanelId === "number") {
            id = createId(indexOrPanelId);
            panelId = id;
          } else {
            panelId = indexOrPanelId;
          }

          const expanded = expandedIds.has(panelId);
          const disabled =
            expanded && preventAllCollapsed && expandedIds.size === 1;
          return {
            id,
            disabled,
            expanded,
            onExpandClick() {
              if (disabled) {
                return;
              }

              setExpandedIds((prevIds) => {
                const expanded = prevIds.has(panelId);
                if (!multiple) {
                  return new Set(expanded ? [] : [panelId]);
                }

                const nextIds = new Set(prevIds);
                if (expanded) {
                  nextIds.delete(panelId);
                } else {
                  nextIds.add(panelId);
                }

                return nextIds;
              });
            },
            disableTransition,
            disableContentPadding,
          };
        },
      };
    }