# All files / tree useTreeExpansion.ts

100% Statements 52/52
100% Branches 8/8
100% Functions 1/1
100% Lines 52/52

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
    531x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    50x
    50x
    50x
    18x
    18x
    4x
    14x
    18x
    18x
    18x
    50x
    50x
    12x
    12x
    12x
    5x
    12x
    7x
    7x
    12x
    12x
    12x
    50x
    50x
    50x
    50x
    50x
    50x
    50x
    50x
     "use client";
    import { useCallback, useState } from "react";
    import type { UseStateSetter } from "../types.js";
    import type { TreeItemDefaultIds, TreeItemIdSet } from "./types.js";

    /**
     * @remarks \@since 6.0.0 Renamed from `TreeItemExpansion` and uses a Set
     * instead of a list to increase performance. Also renamed `onItemExpansion` to
     * `toggleTreeItemExpansion` and `onMultiItemExpansion` to
     * `expandMultipleTreeItems`.
     */
    export interface TreeExpansion {
      expandedIds: TreeItemIdSet;
      toggleTreeItemExpansion(itemId: string): void;
      expandMultipleTreeItems: UseStateSetter<TreeItemIdSet>;
    }

    /**
     * @remarks \@since 6.0.0 Renamed from `useTreeItemExpansion` and uses a Set
     * instead of a list to increase performance.
     */
    export function useTreeExpansion(
      defaultExpandedIds?: TreeItemDefaultIds
    ): TreeExpansion {
      const [expandedIds, setExpandedIds] = useState<TreeItemIdSet>(() => {
        const defaultIds =
          typeof defaultExpandedIds === "function"
            ? defaultExpandedIds()
            : defaultExpandedIds;

        return new Set(defaultIds);
      });

      const toggleTreeItemExpansion = useCallback((itemId: string) => {
        setExpandedIds((prevExpandedIds) => {
          const expandedIds = new Set(prevExpandedIds);
          if (expandedIds.has(itemId)) {
            expandedIds.delete(itemId);
          } else {
            expandedIds.add(itemId);
          }

          return expandedIds;
        });
      }, []);

      return {
        expandedIds,
        toggleTreeItemExpansion,
        expandMultipleTreeItems: setExpandedIds,
      };
    }