# All files / src/main-layout-current useLayoutNavigation.ts

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

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

     import { useEffect, useMemo } from "react";
    import type { CustomLinkComponent } from "../link";
    import { Link } from "../link";
    import type {
      DefaultTreeItemNode,
      TreeData,
      TreeExpansion,
      TreeItemDefaultIds,
      TreeItemNode,
      TreeSelection,
    } from "../tree";
    import { getItemsFrom, useTreeExpansion } from "../tree";

    export interface LayoutNavigationItem extends DefaultTreeItemNode {
      /**
       * Boolean if the item is just a placeholder `Divider` element. None of the
       * other props will be used.
       */
      divider?: boolean;

      /**
       * Boolean if the item is just a placeholder `ListSubheader` element. None of
       * the other props will be used other than `children` with the default item
       * renderer.
       */
      subheader?: boolean;
    }

    /**
     * The layout navigation tree. It is recommended to set this up so that each
     * `itemId` within your tree is the route that the link should be. For example:
     *
     * ```ts
     * const navItems: LayoutNavigationTree = {
     *   "/": {
     *     itemId: "/",
     *     parentId: null,
     *     children: "Home",
     *     leftAddon: <HomeIcon />,
     *     to: "/",
     *     contentComponent: Link,
     *   },
     *   "/route-1": {
     *     itemId: "/route-1",
     *     parentId: null,
     *     children: "Route 1",
     *     leftAddon: <TvIcon />,
     *     to: "/route-1",
     *     contentComponent: Link,
     *   },
     *   "/route-2": {
     *     itemId: "/route-2",
     *     parentId: null,
     *     children: "Route 2",
     *     leftAddon: <AppsIcon />,
     *     to: "/route-2",
     *     contentComponent: Link,
     *   },
     *   "/route-3": {
     *     itemId: "/route-3",
     *     parentId: null,
     *     children: "Route 3",
     *     leftAddon: <BookIcon />,
     *     to: "/route-3",
     *     contentComponent: Link,
     *   },
     * };
     * ```
     *
     * This will work amazingly with the provided `useLayoutNavigation` hook.
     */
    export type LayoutNavigationTree<
      T extends TreeItemNode = LayoutNavigationItem
    > = TreeData<T>;

    export interface LayoutNavigationState<
      T extends TreeItemNode = LayoutNavigationItem
    > extends TreeSelection,
        TreeExpansion {
      /**
       * The navigation items to use that will be passed to the `Tree` component
       * from `@react-md/core`
       */
      data: LayoutNavigationTree<T>;

      /**
       * The link component to use when a nav item is clicked. This defaults to the
       * `Link` component from `@react-md/core`, but can also be a `Link` from
       * `react-router` or another routing library.
       */
      linkComponent: CustomLinkComponent;
    }

    /**
     * @internal
     */
    const getParentIds = (
      itemId: string,
      navItems: TreeData<TreeItemNode>
    ): readonly string[] =>
      getItemsFrom(navItems, itemId).map(({ itemId }) => itemId);

    /**
     * This is used to disable the item select and multi item select functionality
     * since only one id can be selected at a time, and it'll always be the current
     * pathname itemId
     *
     * @internal
     */
    const noop = (): void => {
      // do nothing
    };

    /**
     * This used to just be `pathname.replace(/\?.*$/, "")` but that can apparently
     * cause performance issues or a DoS attack if the pathname contains multiple
     * ?`?` (shouldn't really be possible though)
     *
     * @remarks \@since 2.9.0
     */
    const removeQueryParams = (pathname: string): string => {
      const i = pathname.indexOf("?");
      if (i === -1) {
        return pathname;
      }

      return pathname.substring(0, i);
    };

    export interface LayoutNavigationOptions<
      T extends TreeItemNode = LayoutNavigationItem
    > {
      /**
       * All the navigation items within your layout. This is used for determining
       * which parent tree items should be expanded when the route changes so the
       * current route won't be hidden from view. This sort of flow happens if you
       * have a link outside of the navigation tree.
       */
      navItems: LayoutNavigationTree<T>;

      /**
       * The current pathname
       */
      pathname: string;

      /**
       * The link component to use within the navigation tree for any item that has
       * a `to` or `href` attribute. This defaults to the `Link` from
       * `@react-md/core` but should be changed to whatever link component you need
       * if using a routing library like `react-router`.
       *
       * @defaultValue `Link`
       */
      linkComponent?: CustomLinkComponent;

      /**
       * @defaultValue `getParentIds(pathname, navItems)`
       */
      defaultExpandedIds?: TreeItemDefaultIds;
    }

    /**
     * This is a pretty reasonable default implementation for having a navigation
     * tree within the Layout component. The way it'll work is that the current
     * route will be the only selected item within the tree. When the pathname
     * changes, the selectedIds will be updated to only be the current pathname once
     * again.
     *
     * This means that you can use whatever routing library or history provider that
     * ensures that your layout re-renders on a path change.
     *
     * @see LayoutNavigationTree for description of the navItems
     * @returns the required `Tree` selection and expansion state and handlers that
     * should be passed to the `Layout` component.
     */
    export function useLayoutNavigation<
      T extends TreeItemNode = LayoutNavigationItem
    >(options: LayoutNavigationOptions<T>): LayoutNavigationState<T> {
      const {
        navItems,
        pathname,
        linkComponent = Link,
        defaultExpandedIds,
      } = options;
      const itemId = removeQueryParams(pathname);
      const selectedIds = useMemo(() => new Set([itemId]), [itemId]);
      const { expandedIds, toggleTreeItemExpansion, expandMultipleTreeItems } =
        useTreeExpansion(
          defaultExpandedIds || (() => getParentIds(itemId, navItems))
        );

      useEffect(() => {
        expandMultipleTreeItems((prevExpandedIds) => {
          const nextExpandedIds = new Set([
            ...prevExpandedIds,
            ...getParentIds(itemId, navItems),
          ]);

          return nextExpandedIds;
        });
      }, [expandMultipleTreeItems, itemId, navItems]);

      return {
        data: navItems,
        multiSelect: false,
        linkComponent,
        expandedIds,
        selectedIds,
        expandMultipleTreeItems,
        toggleTreeItemExpansion,
        selectMultipleTreeItems: noop,
        toggleTreeItemSelection: noop,
      };
    }